{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "name": "Kevin_CIS521_midterm_2_notes.ipynb",
      "provenance": [],
      "collapsed_sections": []
    },
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    },
    "language_info": {
      "name": "python"
    }
  },
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "brNDGX-kvzds"
      },
      "source": [
        "# Template for Notes for CIS 521 Midterm 2\n",
        "\n",
        "The midterm exam for CIS 521 will be **open notes**. No other matierals are allowed for the exam - you may not use the textbook, the internet, a Python envionement, or communicate with anyone during the exam. \n",
        "\n",
        "This python notebook is where you should save all of your notes.  It provides a structured template that allows you to add summaries for each of the textbook sections that are part of the required reading, plus room for lecture notes and definitions.\n",
        "\n",
        "Your summaries must be written in your own words.  Do not copy and paste from the textbook.  Do not share your notes with classmates, or copy any of your classmates' notes.  "
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "aPtM8g7R0Pds"
      },
      "source": [
        "# Instructions\n",
        "\n",
        "1. Make a copy of this Google Colab file. From the colab menu, pick **File > Save a copy in Drive**.  That will save a copy of this notebook in your Google drive.\n",
        "2. Go through each section of the notebook, and fill in all the summaries for each chapter and its corresponding sections.  Be sure to save your work frequently!\n",
        "3. Read the notes below about how you can format your summaries.\n",
        "4. In addition to these notes, you are allowed 1 page (both sides) for figures or handwritten notes.\n",
        "5. Submit your version of this notebook to Gradescope before you start the exam.\n",
        "6. If you are taking the exam in person, then you must print a copy of your notes for yourself.   Here's how to print: \n",
        "* Run the last cell of this notebook\n",
        "* Click the \"Mirror cell in tab\" button (this is located in the upper right corner of the cell, immediately to the right of the trash can).  This will open the cell.  \n",
        "* In Chrome, you can then print your notes using the **File > Print** option from the browser's menu.  \n",
        "* In the print options, change the layout from Landscape to Portrait. \n",
        "* Clicking the Save, will save a PDF that you can then print.\n",
        "\n",
        "## Formatting Notes\n",
        "\n",
        "1. The max length for each section's summary is 500 words / 3000 characters.\n",
        "2. You can also write a 2000 word summary of the lectures for each module.\n",
        "3. You may also write definitions of concepts for each module.  The definitions should be written in your own words (not copy and pasted), and they should be no more than 20 words long for each concept. \n",
        "2. You can use Markdown formatting for your summaries. \n",
        "3. You can use Latex formatting for equations. Put two dollar signs before and after your equation like this: \n",
        "$$ \\epsilon = \\frac{1}{mc^2} $$\n",
        "4. When you write python code or psuedocode algorithms, you should surround it with triple backticks like this:\n",
        "```\n",
        "def function():\n",
        "      print('hello world')\n",
        "```\n",
        "5. Write \\ whenever you want to keep writing on the next line without a newline being inserted."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "cw5IpDLCZa4W"
      },
      "source": [
        "## Example summary\n",
        "\n",
        "This is a sample summary of [Section 2.1.1](https://web.stanford.edu/~jurafsky/slp3/2.pdf ) of Jurfasky and Martin's Speech and Language Processing's book\n"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "lzaavW96tcxM",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 0
        },
        "outputId": "51b7fbe1-8d29-4d34-ea84-c22f3ba6174a"
      },
      "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": 37,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "The example summary is 116 words long, so you could write an additional 384 words.\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "s3Uk9gQTevcj"
      },
      "source": [
        "## Example summary length\n",
        "\n",
        "The maximum summary length for each section is 500 words / 3000 characters.  Hopefully you'll find that to be quite generous. "
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "8DvZ57A-djo1",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 0
        },
        "outputId": "0eacf642-cb4c-4354-f86f-86bb9f59f5ee"
      },
      "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": 38,
      "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": 39,
      "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 = \"\"\" Maximum expected utility says rational agent should choose actions that maximize expected utility. MEU doesn't solve ai problem doesn't operationalize what an AI should do, just what it should do.  \"\"\"  + sample_equation\n",
        "chapter16_2 =   \"\"\" MEU is not only rational way for agents to act (could want to minimize loss for example). 6 constraints for preference relations: Orderability (rational agent must prefer one lottery to another or like them equally), Transitivity (If like a over b and b over c, like a over c), Continuity (if b is between a and c, some probability st agent will be indifferent getting b for sure and lottery that gives a with prob p and c with prob 1 - p), subsitutability (if agent is indifferent between a and b, indifferent to two complex lotteries that are teh same except b is substituted for a in one), monotonicity (if two lotteries have same outcome, if agent prefers a to b, prefer lottery with higher chance of a occuring),\n",
        "decomposability (compound lotteries can be reduced via laws of probability). 6 axions of utility theory. If an agent's preferences obey those 6 axioms, than a utility function exists st u(a) = u(b) if indifferent and u(a) > u(b) if prefers a.   \"\"\"\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 = \"\"\" YActions can be unreliable (stochastic). Assume moves are markovian (only depend on current move). MDPS have actions, transition model, and reward function. Methods for solving involve dynamic programming. Solution specifies what must be done at a given state (policy). Denote by pi. Optimal policy yields best expected utility.\n",
        "Optimality of policies depends on reward. Finite horizon vs infinite horizon. Finite means after n moves, game ends. If a policy depends on time, is called nonstationary. Otherwise stationary(like hw). Rewards are additive, with a discount factor so prefers closer rewards. People prefer sooner, and sometimes award may never arrive since stochastic.\n",
        "Can compare policies by comparing expected utilities. With infinite horizon and discounted utilities, optimal policy is independent of starting state. MDPs can't be solved with a fixed number of moves. An optimal policy yields the highest expected utility. Policy is a simple reflex agent.\n",
        "Infinite horizon problems are guaranteed to be stationary (conditional prob table doesn't change over time. ). Q function gives expected value of an action in a state. Bellman equation: Assuming agent chooses best action, utility of state is the expected reward for the next transition plus the discounted utility of the next state.   \"\"\"\n",
        "chapter17_2 =  \"\"\" For value iteration, have n states, so n bellman equations, don't know utilities. Calculate right hand side of equation, fill in left, eventually converge to correct value. Leads to optimal policy. Start with arbitary values, bellman update until equilibrium. Bellman update is contraction by factor of constant discount factor. Possible to get optimal policy with inaccurate utility function.\n",
        "Policy evaulation calculates utility of each step with new policy, than new MEU policy. If meu yields no improvement, stop. For large state spaces, can skip steps, leading to modified policy evaluation. Both aforementioned policies update all states at once, not necessary. Policy evaluation is implemented by using bellman equation. Async iteration is when it only updates a subset of states. Can't solve large mdps with value/policy iteration.\n",
        "\"\"\"\n",
        "\n",
        "# Lecture notes \n",
        "module8_lecture_notes = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "\n",
        "# Definitions of concepts from Module 8.\n",
        "# You can define any term in the textbook or lecture, \n",
        "# but you most use your own words for the definitions.\n",
        "# Each definition should be at most 25 words long.\n",
        "\n",
        "module8_definitions = {\n",
        "\"utility function\" : \"Assigns number to express state's desirability\",\n",
        "\"expected utility\" : \"Average utility over outcomes\",\n",
        "\"environment history\" : \"sequence of state and actions\",\n",
        "\"Markov decision process\" : \"sequential decision problem for fully oberservable stochastic environments\",\n",
        "\"proper policy\" : \"policy guaranteed to reach terminal state\",\n",
        "\"Q function\" : \"Gives expected utility of taking action in a state\",\n",
        "\"Bellman equation\" : \"expected reward  for next transition + discounted utility of next state, assuming optimal action\",\n",
        "\"contraction\" : \"function of an argument that when applied to two inputs, produces two values closer together. (Divide by two)\",\n",
        "}\n",
        "\n"
      ],
      "execution_count": 40,
      "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": 1052
        },
        "outputId": "7628c7db-0d0b-455e-eb35-2f03db507aad"
      },
      "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": 41,
      "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 Maximum expected utility says rational agent should choose actions that maximize expected utility. MEU doesn't solve ai problem doesn't operationalize what an AI should do, just what it should do.   $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 MEU is not only rational way for agents to act (could want to minimize loss for example). 6 constraints for preference relations: Orderability (rational agent must prefer one lottery to another or like them equally), Transitivity (If like a over b and b over c, like a over c), Continuity (if b is between a and c, some probability st agent will be indifferent getting b for sure and lottery that gives a with prob p and c with prob 1 - p), subsitutability (if agent is indifferent between a and b, indifferent to two complex lotteries that are teh same except b is substituted for a in one), monotonicity (if two lotteries have same outcome, if agent prefers a to b, prefer lottery with higher chance of a occuring),\ndecomposability (compound lotteries can be reduced via laws of probability). 6 axions of utility theory. If an agent's preferences obey those 6 axioms, than a utility function exists st u(a) = u(b) if indifferent and u(a) > u(b) if prefers a.   \n\n## AIMA Chapter 16.3 Utility Functions\n Your summary here \n\n## AIMA Chapter 17.1 Sequential Decision Problems\n YActions can be unreliable (stochastic). Assume moves are markovian (only depend on current move). MDPS have actions, transition model, and reward function. Methods for solving involve dynamic programming. Solution specifies what must be done at a given state (policy). Denote by pi. Optimal policy yields best expected utility.\nOptimality of policies depends on reward. Finite horizon vs infinite horizon. Finite means after n moves, game ends. If a policy depends on time, is called nonstationary. Otherwise stationary(like hw). Rewards are additive, with a discount factor so prefers closer rewards. People prefer sooner, and sometimes award may never arrive since stochastic.\nCan compare policies by comparing expected utilities. With infinite horizon and discounted utilities, optimal policy is independent of starting state. MDPs can't be solved with a fixed number of moves. An optimal policy yields the highest expected utility. Policy is a simple reflex agent.\nInfinite horizon problems are guaranteed to be stationary (conditional prob table doesn't change over time. ). Q function gives expected value of an action in a state. Bellman equation: Assuming agent chooses best action, utility of state is the expected reward for the next transition plus the discounted utility of the next state.   \n\n## AIMA Chapter 17.2 Algorithms for MDPs\n For value iteration, have n states, so n bellman equations, don't know utilities. Calculate right hand side of equation, fill in left, eventually converge to correct value. Leads to optimal policy. Start with arbitary values, bellman update until equilibrium. Bellman update is contraction by factor of constant discount factor. Possible to get optimal policy with inaccurate utility function.\nPolicy evaulation calculates utility of each step with new policy, than new MEU policy. If meu yields no improvement, stop. For large state spaces, can skip steps, leading to modified policy evaluation. Both aforementioned policies update all states at once, not necessary. Policy evaluation is implemented by using bellman equation. Async iteration is when it only updates a subset of states. Can't solve large mdps with value/policy iteration.\n\n\n## Module 8 Lecture Notes\n Your summary here \n\n## Module 8 Definitions\n* **Utility function** - Assigns number to express state's desirability\n* **Expected utility** - Average utility over outcomes\n* **Environment history** - sequence of state and actions\n* **Markov decision process** - sequential decision problem for fully oberservable stochastic environments\n* **Proper policy** - policy guaranteed to reach terminal state\n* **Q function** - Gives expected utility of taking action in a state\n* **Bellman equation** - expected reward  for next transition + discounted utility of next state, assuming optimal action\n* **Contraction** - function of an argument that when applied to two inputs, produces two values closer together. (Divide by two)\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 =  \"\"\" N armed bandit: slot machine with n levers, different prob dists. Do you pull level with best known payoff (exploitation) or the lever you haven't tried yet (exploration). One way to think of bandit problem is each arm is a mdp with one action, and entire machine is mdp. Bernoulli bandit: bandit problem where arm produces 0 or 1.\n",
        " \"\"\"\n",
        "\n",
        "# Russell and Norvig, AIMA Chapter 22 “Reinforcement Learning” (Sections 22.1-22.5)\n",
        "chapter22_1 =  \"\"\" Rewards are sparse when few states give the agent info. In reinforcement learning, agent is in MDP but not given mdp to solve (doesn't know transition/reward function.) Easier to provide reward signals than labels. Sparse rewards make learning much harder.\n",
        "1  \"\"\"\n",
        "chapter22_2 =  \"\"\" Passive learning is like policy evaluation, however doesn't know transition model or reward function. Agent does amount of trials with a policy, keeps track of rewards received and action taken. DUE keeps average, over infinite trials would eventually converge to true expectation.\n",
        " However, ignores state connections. Adaptive dynamic programming learns transition model that connects states. Easy as model is fully observable. Direct utility estimation turns reinforcement learning into supervised learning. Ignores connection between states.   \"\"\"\n",
        "chapter22_3 =  \"\"\" Agent needs to learn transition model. Greedy agents often fail as what they think is optimal actually isn't. Should be GLIE, which must take every action some number of times. Can give weight to options not tried yet. Much faster than strictly greedy\n",
        "Some actions are irreversible and can lead to absorbing states (no actions matter/no rewards). Q learning method avoids need for model, learns q function instead.  \"\"\"\n",
        "chapter22_4 =  \"\"\" In real world environments, convergence will be too slow with previous methods. Use function approximation to construct approximation of q function. Allows agent to make generalizations about states it hasn't visited. Direct utility estimations attempts to extract sum of rewards received at that state until termination.\n",
        " \"\"\"\n",
        "chapter22_5 =  \"\"\" Policy search simply adjusts the policy until performance improves than stops.  \"\"\"\n",
        "\n",
        "\n",
        "# Lecture notes \n",
        "module9_lecture_notes = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "# Each definition should be at most 25 words long.\n",
        "module9_definitions = {\n",
        "\"reinforcement learning\" : \"agent interacts with world, occasionally receiving rewards based on how it performs, doesn't need labels\",\n",
        "\"model based rl\" : \"agent uses transition model to interpret rewards and make decisions\",\n",
        "\"model free rl\" : \"No transition model, either action utlity learning (q function) or policy search(mdp)\",\n",
        "\"passive rl\" : \"policy is fixed, agent wants to learn state utilities, similar to policy evaluation, doesnt know reward/transition\",\n",
        "\"active rl\" : \"agent must figure out what to do, explore\",\n",
        "\"direct utility estimation\" : \"utility of state is defined as expected total reward from state on, each trial is a sample.\",\n",
        "\"temporal difference learning\" : \"use transitions to adjust state utilities\",\n",
        "\"Greedy agent\" : \"Takes what it thinks is optimal choice at each step\",\n",
        "\"reward-to-go\" : \"total reward from a given state onward give a particular policy\",\n",
        "\"\" : \"\",\n",
        "\"\" : \"\",\n",
        "}"
      ],
      "execution_count": 42,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "ydOK__lwWgdp",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 909
        },
        "cellView": "form",
        "outputId": "7885d182-8b13-408e-c9d3-6cb0a9295687"
      },
      "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": 43,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 9: Reinforcement Learning\n## AIMA Chapter 17.3 Bandit Problems\n N armed bandit: slot machine with n levers, different prob dists. Do you pull level with best known payoff (exploitation) or the lever you haven't tried yet (exploration). One way to think of bandit problem is each arm is a mdp with one action, and entire machine is mdp. Bernoulli bandit: bandit problem where arm produces 0 or 1.\n \n\n## AIMA Chapter 22.1 Learning from Rewards\n Rewards are sparse when few states give the agent info. In reinforcement learning, agent is in MDP but not given mdp to solve (doesn't know transition/reward function.) Easier to provide reward signals than labels. Sparse rewards make learning much harder.\n1  \n\n## AIMA Chapter 22.2 Passive Reinforcement Learning\n Passive learning is like policy evaluation, however doesn't know transition model or reward function. Agent does amount of trials with a policy, keeps track of rewards received and action taken. DUE keeps average, over infinite trials would eventually converge to true expectation.\n However, ignores state connections. Adaptive dynamic programming learns transition model that connects states. Easy as model is fully observable. Direct utility estimation turns reinforcement learning into supervised learning. Ignores connection between states.   \n\n## AIMA Chapter 22.3 Active Reinforcement Learning\n Agent needs to learn transition model. Greedy agents often fail as what they think is optimal actually isn't. Should be GLIE, which must take every action some number of times. Can give weight to options not tried yet. Much faster than strictly greedy\nSome actions are irreversible and can lead to absorbing states (no actions matter/no rewards). Q learning method avoids need for model, learns q function instead.  \n\n## AIMA Chapter 22.4 Generalization in Reinforcement Learning\n In real world environments, convergence will be too slow with previous methods. Use function approximation to construct approximation of q function. Allows agent to make generalizations about states it hasn't visited. Direct utility estimations attempts to extract sum of rewards received at that state until termination.\n \n\n## Module 9 Lecture Notes\n Your summary here \n\n## Module 9 Definitions\n* **Reinforcement learning** - agent interacts with world, occasionally receiving rewards based on how it performs, doesn't need labels\n* **Model based rl** - agent uses transition model to interpret rewards and make decisions\n* **Model free rl** - No transition model, either action utlity learning (q function) or policy search(mdp)\n* **Passive rl** - policy is fixed, agent wants to learn state utilities, similar to policy evaluation, doesnt know reward/transition\n* **Active rl** - agent must figure out what to do, explore\n* **Direct utility estimation** - utility of state is defined as expected total reward from state on, each trial is a sample.\n* **Temporal difference learning** - use transitions to adjust state utilities\n* **Greedy agent** - Takes what it thinks is optimal choice at each step\n* **Reward-to-go** - total reward from a given state onward give a particular policy\n* **** - \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 = \"\"\" An agent may never know what state its in or where it will be (uncertainity). Using logic for a domain can fail for 3 reasons: Laziness, list of complete antecedents or consequents is too long, theoritical ignorance, no complete theory, practical ignorance, don't have all of the details.\n",
        "Solved by probability theory. Might not be certain, but have good idea. Agents must have preferences for outcomes (utility theory). Decision theory combines probability theory and utility theory.   \"\"\"\n",
        "chapter12_2 = \"\"\"  \"\"\"\n",
        "chapter12_3 = \"\"\"  \"\"\"\n",
        "chapter12_4 = \"\"\" Variables are independent is P(a) * P(b) = P(a and b). Bayes rule with background evidence: P(y|x, e) = P(x|y,e)P(y|e)/P(x). General form puts alpha in front of P(x|y)P(y) for product rule.\n",
        "Diagnostic info (cause|effect) more fragile than causal (effect|cause). \"\"\"\n",
        "chapter12_5 = \"\"\" Your summary here \"\"\"\n",
        "chapter12_6 = \"\"\" Naive bayes: P(cause, effect_1-n) = P(cause) product of P(effect_i|cause). Often used for text classification \"\"\"\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 = \"\"\" For ngrams, history isn't the best way to generate probabilities since new sentences are created often. Can use chainrule of prob, product of P(X_k|X_1-k-1). Can also approximate history using last few words (break down into bigrams). Assumption is markovian.\n",
        " \"\"\"\n",
        "SLP_chapter3_2 = \"\"\"  \"\"\"\n",
        "SLP_chapter3_3 = \"\"\" Your summary here \"\"\"\n",
        "SLP_chapter3_4 = \"\"\" Should try to make sure training and test data have similar genre (shakespeare vs wsj). Some models may also have words that occur with 0 probability even they they are possible combinations. Ok for closed vocabularies. For open vocabs, add marker called unk. Perplexity should only be compared for language models with same vocab.\n",
        " \"\"\"\n",
        "SLP_chapter3_5 = \"\"\" Laplace smoothing adds 1 to every count.  \"\"\"\n",
        "SLP_chapter3_7 = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "\n",
        "# Lecture notes \n",
        "module10_lecture_notes = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "\n",
        "# Each definition should be at most 25 words long.\n",
        "module10_definitions = {\n",
        "\"belief state\" : \"set of possible states the agent could be in (too large)\",\n",
        "\"rational decision\" : \"depends on relative important of goals and their likelihood of success\",\n",
        "\"condition probability\" : \"P(A|b) = P(A and B)/P(b) (bayes rule)\",\n",
        "\"product rule\" : \"p(a and b) = p(a|b)p(b)\",\n",
        "\"marginal probability\" : \"unconditional probability\",\n",
        "\"extrinsic evaluation\" : \"embed language model in application, see if it improves (expensive)\",\n",
        "\"intrinsic evaluation\" : \"measures independent of application\",\n",
        "\"perplexity\" : \"Used to evaluate models, weighted average branching factor of a language. More info = less perplexity\",\n",
        "\"smoothing\" : \"allocate probability from frequently seen occurences to never seen occurences\",\n",
        "\"\" : \"\",\n",
        "}"
      ],
      "execution_count": 44,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "lvtN3p7ET3Tx",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1286
        },
        "cellView": "form",
        "outputId": "4afb91c0-d46d-4958-c312-625aa0c5595d"
      },
      "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": 45,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 10: Probabilies and Language Models\n## AIMA Chapter 12.1 Acting under Uncertainty\n An agent may never know what state its in or where it will be (uncertainity). Using logic for a domain can fail for 3 reasons: Laziness, list of complete antecedents or consequents is too long, theoritical ignorance, no complete theory, practical ignorance, don't have all of the details.\nSolved by probability theory. Might not be certain, but have good idea. Agents must have preferences for outcomes (utility theory). Decision theory combines probability theory and utility theory.   \n\n## AIMA Chapter 12.2 Basic Probability Notation\n  \n\n## AIMA Chapter 12.3 Inference Using Full Joint Distributions\n  \n\n## AIMA Chapter 12.4 Independence\n Variables are independent is P(a) * P(b) = P(a and b). Bayes rule with background evidence: P(y|x, e) = P(x|y,e)P(y|e)/P(x). General form puts alpha in front of P(x|y)P(y) for product rule.\nDiagnostic info (cause|effect) more fragile than causal (effect|cause). \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 Naive bayes: P(cause, effect_1-n) = P(cause) product of P(effect_i|cause). Often used for text classification \n\n## AIMA Chapter 12.7 The Wumpus World Revisited\n Your summary here \n\n## SLP Chapter 3.1 N-Grams\n For ngrams, history isn't the best way to generate probabilities since new sentences are created often. Can use chainrule of prob, product of P(X_k|X_1-k-1). Can also approximate history using last few words (break down into bigrams). Assumption is markovian.\n \n\n## SLP Chapter 3.2 Evaluating Language Models\n  \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 Should try to make sure training and test data have similar genre (shakespeare vs wsj). Some models may also have words that occur with 0 probability even they they are possible combinations. Ok for closed vocabularies. For open vocabs, add marker called unk. Perplexity should only be compared for language models with same vocab.\n \n\n## SLP Chapter 3.5 Smoothing\n Laplace smoothing adds 1 to every count.  \n\n## SLP Chapter 3.7 Huge Language Models and Stupid Backoff\n Your summary here \n\n## Module 10 Lecture Notes\n Your summary here \n\n## Module 10 Definitions\n* **Belief state** - set of possible states the agent could be in (too large)\n* **Rational decision** - depends on relative important of goals and their likelihood of success\n* **Condition probability** - P(A|b) = P(A and B)/P(b) (bayes rule)\n* **Product rule** - p(a and b) = p(a|b)p(b)\n* **Marginal probability** - unconditional probability\n* **Extrinsic evaluation** - embed language model in application, see if it improves (expensive)\n* **Intrinsic evaluation** - measures independent of application\n* **Perplexity** - Used to evaluate models, weighted average branching factor of a language. More info = less perplexity\n* **Smoothing** - allocate probability from frequently seen occurences to never seen occurences\n* **** - \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 = \"\"\" Bayesian networks can in effect represent the dependence among variables, and even any full joint prob distribution. Bayes nets are directed graphs, each node is random variable, if edge from x to y x is parent, each node has probability x given its parents, which helps show the effect of parents on the node.\n",
        "\"\"\"\n",
        "chapter13_2 = \"\"\" To construct bayes net, set nodes, label 1-n, set appropriate edges (minimal, parents). Parents should be nodes that have direct influence on node. This guarantees acyclic. Bayes can be more compact than full joint dist.\n",
        "Sparse/locally structured system, linear. Must choose node ordering well. In bayes nets, variables are conditionally independent on non descendants, and conditionally independent of all nodes in the network given its parents, childrens, children's parents, its markov blanket. \n",
        "D separation of x, y, z- consider subgraph of x, y, z, and ancestors, add links between unlinked nodes that have a common child, replace directed with undirected, if z blocks all paths between x and y, z d separates x and y. If so, x conditionally independent of y.\n",
        " A way to handle continuous variables is discretization of variables. Loss of accuracy, slower. Also can use probability density function, \"\"\"\n",
        "chapter13_3 = \"\"\"  \"\"\"\n",
        "\n",
        "\n",
        "# Lecture notes \n",
        "module11_lecture_notes = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "# Definitions\n",
        "module11_definitions = {\n",
        "\"Chain rule\" : \"P(X_i|X_1-i-1) = P(X_i|Parents(X_i))\",  \n",
        "\"determinisitic node\" : \"node's value is determined by its parents\",  \n",
        "}\n"
      ],
      "execution_count": 46,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "vqtEs0gHs9sO",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 543
        },
        "cellView": "form",
        "outputId": "64d44c60-b3eb-4774-c35f-77131b3b0ceb"
      },
      "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": 47,
      "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 Bayesian networks can in effect represent the dependence among variables, and even any full joint prob distribution. Bayes nets are directed graphs, each node is random variable, if edge from x to y x is parent, each node has probability x given its parents, which helps show the effect of parents on the node.\n\n\n## AIMA Chapter 13.2 The Semantics of Bayesian Networks\n To construct bayes net, set nodes, label 1-n, set appropriate edges (minimal, parents). Parents should be nodes that have direct influence on node. This guarantees acyclic. Bayes can be more compact than full joint dist.\nSparse/locally structured system, linear. Must choose node ordering well. In bayes nets, variables are conditionally independent on non descendants, and conditionally independent of all nodes in the network given its parents, childrens, children's parents, its markov blanket. \nD separation of x, y, z- consider subgraph of x, y, z, and ancestors, add links between unlinked nodes that have a common child, replace directed with undirected, if z blocks all paths between x and y, z d separates x and y. If so, x conditionally independent of y.\n A way to handle continuous variables is discretization of variables. Loss of accuracy, slower. Also can use probability density function, \n\n## AIMA 13.3 Exact Inference in Bayesian Networks\n  \n\n## Module 11 Lecture Notes\n Your summary here \n\n## Module 11 Definitions\n* **Chain rule** - P(X_i|X_1-i-1) = P(X_i|Parents(X_i))\n* **Determinisitic node** - node's value is determined by its parents\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 = \"\"\" Three main types of learning: supervised learning, agent learns, predicts labels for actions. Unsupervised learning, learns inputs without explicit feedback, reinforcement learning, agent learns from reinforcement. \n",
        " \"\"\"\n",
        "chapter19_2 = \"\"\" Can analyze hypothesis space by its bias. True to trade off between bias and variances. Linear has lots of bias. \"\"\"\n",
        "chapter19_3 = \"\"\" Learn decision tree algo: start with most important problem, recursively solve smaller subproblems. Can skip some features if they aren't relevant to the solution. Can evaluate performance with learning curve, proportion of correct over training set size.\n",
        "More attributes means overfitting is more likely. To combat overfitting, use decision tree pruning, prune irrelevant nodes.   \"\"\"\n",
        "chapter19_4 = \"\"\"  \"\"\"\n",
        "chapter19_5 = \"\"\"  \"\"\"\n",
        "chapter19_6 = \"\"\" \"\"\"\n",
        "\n",
        "# Speech and Language Processing Chapter 4 “Naive Bayes and Sentiment Classification”\n",
        "slp_chapter4_1 = \"\"\" Bag of words representation only keeps the frequency of words in a doc. Another naive bayes assumption is that the probability of features given a class are independent. Called a linear classifier \"\"\"\n",
        "slp_chapter4_2 = \"\"\" With naive bayes, can use frequencies in data to learn probabilities. Can use laplace smoothing in case of zero probabilties since they are all multiplied together. We also ignore unknown words. Can also ignore stop words. \"\"\"\n",
        "slp_chapter4_3 = \"\"\"   \"\"\"\n",
        "slp_chapter4_4 = \"\"\"  \"\"\"\n",
        "slp_chapter4_5 = \"\"\"  \"\"\"\n",
        "slp_chapter4_6 = \"\"\"  \"\"\"\n",
        "slp_chapter4_7 = \"\"\" \"\"\"\n",
        "slp_chapter4_8 = \"\"\" \"\"\"\n",
        "slp_chapter4_9 = \"\"\"  \"\"\"\n",
        "slp_chapter4_10 = \"\"\" \"\"\"\n",
        "\n",
        "# Lecture notes \n",
        "module12_lecture_notes = \"\"\" Perceptrons use error driven learning. Takes in inputs, multiplies them by weight, takes sum, use as input to activation function. Perceptrons try to learn the weight vector. Inputs are features we want to classify. \n",
        "Inputs are fixed, can only change weight. To learn weights, classify with current weights. If correct, no change, otherwise, adjust weight. \"\"\"\n",
        "\n",
        "# Definitions\n",
        "module12_definitions = {\n",
        "\"bias\" : \"deviation from expected value\",  \n",
        "\"decision tree\" : \"maps inputs to single output\",  \n",
        "\"\" : \"\",  \n",
        "\"\" : \"\",  \n",
        "\"\" : \"\",  \n",
        "\"\" : \"\",  \n",
        "\"\" : \"\",  \n",
        "\"\" : \"\",  \n",
        "\"\" : \"\",       \n",
        "}\n",
        "\n"
      ],
      "execution_count": 48,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "KUc_LgzDvWf-",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1178
        },
        "outputId": "494e11e4-c7bc-47ea-983b-259bfff4938c"
      },
      "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": 49,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 12: Naive Bayes and Perceptrons\n## AIMA Chapter 5.1 Game Theory\n Three main types of learning: supervised learning, agent learns, predicts labels for actions. Unsupervised learning, learns inputs without explicit feedback, reinforcement learning, agent learns from reinforcement. \n \n\n## AIMA Chapter 5.2 Optimal Decisions in Games\n Can analyze hypothesis space by its bias. True to trade off between bias and variances. Linear has lots of bias. \n\n## AIMA Chapter 5.3 Heuristic Alpha–Beta Tree Search\n Learn decision tree algo: start with most important problem, recursively solve smaller subproblems. Can skip some features if they aren't relevant to the solution. Can evaluate performance with learning curve, proportion of correct over training set size.\nMore attributes means overfitting is more likely. To combat overfitting, use decision tree pruning, prune irrelevant nodes.   \n\n## AIMA Chapter 5.5 Stochastic Games\n  \n\n## AIMA Chapter 16.1 Combining Beliefs and Desires under Uncertainty\n  \n\n## AIMA Chapter 16.2 The Basis of Utility Theory\n \n\n## SLP Chapter 4.1 Naive Bayes Classifiers\n Bag of words representation only keeps the frequency of words in a doc. Another naive bayes assumption is that the probability of features given a class are independent. Called a linear classifier \n\n## SLP Chapter 4.2 Training the Naive Bayes Classifier\n With naive bayes, can use frequencies in data to learn probabilities. Can use laplace smoothing in case of zero probabilties since they are all multiplied together. We also ignore unknown words. Can also ignore stop words. \n\n## SLP Chapter 4.3 Worked Example\n   \n\n## SLP Chapter 4.4 Optimizing for Sentiment Analysis\n  \n\n## SLP Chapter 4.5 Naive Bayes for other text classification tasks\n  \n\n## SLP Chapter 4.6 Naive Bayes as a Language Model\n  \n\n## SLP Chapter 4.7 Evaluation: Precision, Recall, F-measure\n \n\n## SLP Chapter 4.8 Test sets and Cross-validation\n \n\n## SLP Chapter 4.9 Statistical Significance Testing\n  \n\n## SLP Chapter 4.10 Avoiding Harms in Classification\n \n\n## Module 12 Lecture Notes\n Perceptrons use error driven learning. Takes in inputs, multiplies them by weight, takes sum, use as input to activation function. Perceptrons try to learn the weight vector. Inputs are features we want to classify. \nInputs are fixed, can only change weight. To learn weights, classify with current weights. If correct, no change, otherwise, adjust weight. \n\n## Module 12 Definitions\n* **Bias** - deviation from expected value\n* **Decision tree** - maps inputs to single output\n* **** - \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 = \"\"\" Map output of regression to sigmoid function to give real valued output. Sigmoid makes it so z is between 0 and 1. If sigmoid returns .5 or greater, 1, else 0. Naive Bayes has very strong conditional independence assumptions, where as logisitic regression does not.\n",
        "   \"\"\"\n",
        "slp_chapter5_2 = \"\"\" Need loss/cost function/ gradient function. \"\"\"\n",
        "slp_chapter5_3 = \"\"\" Use conditional maximum likelihood estimation, choose w and b to maximize log probability of the correct y labels in the training data. Resulting loss function is negative log likelihood loss, called cross-entropy loss.  \"\"\"\n",
        "slp_chapter5_4 = \"\"\" Gradient descent goal is to find optimal weights/minimize loss function. Finds direction slop rises in most steeply, and goes in the opposite direction. This is convex for logistic regression \"\"\"\n",
        "slp_chapter5_5 = \"\"\"  \"\"\"\n",
        "slp_chapter5_6 = \"\"\"  \"\"\"\n",
        "\n",
        "# Jurafsky and Martin, Chapter 7 “Neural Networks and Neural Language Models”\n",
        "\n",
        "slp_chapter7_1 = \"\"\" Neural networks are similar to logistical regression, but are more powerful (only need one layer to learn any function). Instead of handderived features, take raw words as inputs. Computational unit takes weighted sum of inputs + bias.\n",
        "Ontop of sigmoid, also have ReLU, which is max(z, 0). Also tanh. (e^z-e^-z)/(e^z+e^-z). Tanh is smoothly differentiable, maps outliers towards mean. ReLU is nearly linear, prevents derivatives from being close to 0, which we want. \"\"\"\n",
        "slp_chapter7_2 = \"\"\" A single perceptron can't computer xor. Means xor is not linearly separable. Xor can be calculated by a \"layered network of units\".  \"\"\"\n",
        "slp_chapter7_3 = \"\"\" Feedforward network is a network with no cycles, multi layered, outputs pass to next layer, cant pass back. Not made of perceptrons anymore. Layers are fully connected, so each unit takes input from all units in previous layer.\n",
        " \"\"\"\n",
        "slp_chapter7_4 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter7_5 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter7_6 = \"\"\" To train a neural net, need loss function (cross entropy loss). Need to know gradient of loss function. Computed via error backpropagation. \"\"\"\n",
        "slp_chapter7_7 = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "# Lecture notes \n",
        "module13_lecture_notes = \"\"\" ML classifiers have a feature representation, classification function, objective function (how good algo is), and an optimization algo. Logistic regression learns weight for each input and a bias term. \n",
        "Difference from perceptron is range of outputs. To get the weights use loss function that tells us distance between system output and gold output, and algo to minimize loss function (how much output differs from correct output).\n",
        "Neural network built of many logistic regressions (not perceptrons?). Out is put through sigmoid function, makes updating weight easier. Generally just computational units. To train neural networks, need loss function, optimization algo,\n",
        "and a way of computing gradient of a loss function. error Backpropagatiion algo helps calculate gradient for all layers. yy  \"\"\"\n",
        "\n",
        "# Definitions\n",
        "module13_definitions = {\n",
        "\"concept\" : \"definition\",    \n",
        "}\n"
      ],
      "execution_count": 50,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "kKWbCsbfxL3R",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1258
        },
        "cellView": "form",
        "outputId": "ad269945-d982-4e77-e79c-778c226140ef"
      },
      "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": 51,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 13: Neural Networks\n## SLP Chapter 5.1 Classification: the sigmoid\n Map output of regression to sigmoid function to give real valued output. Sigmoid makes it so z is between 0 and 1. If sigmoid returns .5 or greater, 1, else 0. Naive Bayes has very strong conditional independence assumptions, where as logisitic regression does not.\n   \n\n## SLP Chapter 5.2 Learning in Logistic Regression\n Need loss/cost function/ gradient function. \n\n## SLP Chapter 5.3 The cross-entropy loss function\n Use conditional maximum likelihood estimation, choose w and b to maximize log probability of the correct y labels in the training data. Resulting loss function is negative log likelihood loss, called cross-entropy loss.  \n\n## SLP Chapter 5.4 Gradient Descent\n Gradient descent goal is to find optimal weights/minimize loss function. Finds direction slop rises in most steeply, and goes in the opposite direction. This is convex for logistic regression \n\n## SLP Chapter 5.5 Regularization\n  \n\n## SLP Chapter 5.6 Multinomial logistic regression\n  \n\n## SLP Chapter 7.1 Units\n Neural networks are similar to logistical regression, but are more powerful (only need one layer to learn any function). Instead of handderived features, take raw words as inputs. Computational unit takes weighted sum of inputs + bias.\nOntop of sigmoid, also have ReLU, which is max(z, 0). Also tanh. (e^z-e^-z)/(e^z+e^-z). Tanh is smoothly differentiable, maps outliers towards mean. ReLU is nearly linear, prevents derivatives from being close to 0, which we want. \n\n## SLP Chapter 7.2 The XOR problem\n A single perceptron can't computer xor. Means xor is not linearly separable. Xor can be calculated by a \"layered network of units\".  \n\n## SLP Chapter 7.3 Feedforward Neural Networks\n Feedforward network is a network with no cycles, multi layered, outputs pass to next layer, cant pass back. Not made of perceptrons anymore. Layers are fully connected, so each unit takes input from all units in previous layer.\n \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 To train a neural net, need loss function (cross entropy loss). Need to know gradient of loss function. Computed via error backpropagation. \n\n## SLP Chapter 7.7 Training the neural language model\n Your summary here \n\n## Module 13 Lecture Notes\n ML classifiers have a feature representation, classification function, objective function (how good algo is), and an optimization algo. Logistic regression learns weight for each input and a bias term. \nDifference from perceptron is range of outputs. To get the weights use loss function that tells us distance between system output and gold output, and algo to minimize loss function (how much output differs from correct output).\nNeural network built of many logistic regressions (not perceptrons?). Out is put through sigmoid function, makes updating weight easier. Generally just computational units. To train neural networks, need loss function, optimization algo,\nand a way of computing gradient of a loss function. error Backpropagatiion algo helps calculate gradient for all layers. yy  \n\n## Module 13 Definitions\n* **Concept** - definition\n",
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "RYESi2kMybL8"
      },
      "source": [
        "# Module 14 - Natural Language Processing"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "qIRJ4YYCzNHL"
      },
      "source": [
        "# Jurafsky and Martin, Chapter 9 “Sequence Processing with Recurrent Networks” (Sections 9.1-9.3)\n",
        "\n",
        "slp_chapter9_1 = \"\"\"  \"\"\"\n",
        "slp_chapter9_2 = \"\"\"  a recurrent neural network contains cycles. \"\"\"\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 = \"\"\" Vector semantics main idea is to represent a word as a point in space that is derived from the distribution of its neighbors. Word vectors are called embeddings. Two main models: tf-idf, based on nearby word count, and word2vec, which produce dense(tf-idf is sprase) vectors with semantic properties.\n",
        " \"\"\"\n",
        "slp_chapter6_3 = \"\"\" In term doc matrix, row represents word, column represents a document. Cell is how many times word appeared in doc. Information retrieval is trying to find the document that best matches the query.  \"\"\"\n",
        "slp_chapter6_4 = \"\"\" To measure similiarity of two word vectors, take cosine of the angle between them. Raw dot product favors longer vectors. To solve this we normalize the dot product. \"\"\"\n",
        "slp_chapter6_8 = \"\"\" Embeddings are short dense vectors. Work better in every nlp task than sparse vectors. One way of computing embeddings is skip gram with negative sampling. Don't count how often word x appears near word y, but train \"is x likely to appear near y? Essentially self supervision.\n",
        "Skipgram: treat target word and neighbor as positive examples, randomly sample other words to get negative sample, use logistic regression to train classifier on two cases, use learned weights as embeddings.\n",
        " \"\"\"\n",
        "slp_chapter6_10 = \"\"\"  \"\"\"\n",
        "slp_chapter6_11 = \"\"\" Your summary here \"\"\"\n",
        "slp_chapter6_12 = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "\n",
        "\n",
        "# Lecture notes \n",
        "module14_lecture_notes = \"\"\" How to estimate probability of sentence/words? Have seen ngrams, language models. What we've seen before has a sparsity problem. Probability could be 0 at test time. Neural language models don't need smoothing, can handle longer histories,\n",
        "generalize, and higher predictive accuracy. Associate each word with vector representation, express joint probability function, learn word vectors and parameters of the function. Input is gonna be a kgram, output is a prob distribution. Input is fed into neural network with 1 or more hidden layers.\n",
        "Also have term by term matrix, rows and columns are both just words. Cell represents how often column word appears in context window surrounding row word. Context windows occur of +/- 2 words, in the same sentence in the same document. Can also use dependency parsing,\n",
        "tells syntactic relationship (if are is in the sentence, has to be plural, etc), follow dependency arc. Transform raw counts since some words are very frequent. Tf idf is term frequency * inverse of #documents it appears in. So the will appear in probably all of them.\n",
        " \n",
        " \"\"\"\n",
        "\n",
        "# Definitions\n",
        "module14_definitions = {\n",
        "\"concept\" : \"definition\",    \n",
        "}\n",
        "\n"
      ],
      "execution_count": 52,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "lXNcHuKjyNXa",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1106
        },
        "outputId": "2ed74031-293f-4e8c-9ed1-ff17418559dc"
      },
      "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": 53,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 14: Natural Language Processing\n## SLP Chapter 9.1 Language Models Revisited\n  \n\n## SLP Chapter 9.2 Recurrent Neural Networks\n  a recurrent neural network contains cycles. \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 Vector semantics main idea is to represent a word as a point in space that is derived from the distribution of its neighbors. Word vectors are called embeddings. Two main models: tf-idf, based on nearby word count, and word2vec, which produce dense(tf-idf is sprase) vectors with semantic properties.\n \n\n## SLP Chapter 6.3 Words and Vectors\n In term doc matrix, row represents word, column represents a document. Cell is how many times word appeared in doc. Information retrieval is trying to find the document that best matches the query.  \n\n## SLP Chapter 6.4 Cosine for measuring similarity\n To measure similiarity of two word vectors, take cosine of the angle between them. Raw dot product favors longer vectors. To solve this we normalize the dot product. \n\n## SLP Chapter 6.8 Word2vec\n Embeddings are short dense vectors. Work better in every nlp task than sparse vectors. One way of computing embeddings is skip gram with negative sampling. Don't count how often word x appears near word y, but train \"is x likely to appear near y? Essentially self supervision.\nSkipgram: treat target word and neighbor as positive examples, randomly sample other words to get negative sample, use logistic regression to train classifier on two cases, use learned weights as embeddings.\n \n\n## SLP Chapter 6.10 Semantic properties of embeddings\n  \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 ML classifiers have a feature representation, classification function, objective function (how good algo is), and an optimization algo. Logistic regression learns weight for each input and a bias term. \nDifference from perceptron is range of outputs. To get the weights use loss function that tells us distance between system output and gold output, and algo to minimize loss function (how much output differs from correct output).\nNeural network built of many logistic regressions (not perceptrons?). Out is put through sigmoid function, makes updating weight easier. Generally just computational units. To train neural networks, need loss function, optimization algo,\nand a way of computing gradient of a loss function. error Backpropagatiion algo helps calculate gradient for all layers. yy  \n\n## Module 14 Definitions\n* **Concept** - definition\n",
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "vX7lbnJd4sT5"
      },
      "source": [
        "# Your Exam Notes\n",
        "\n",
        "Here are your full set of exam notes that you can use on your midterm.  Choose **Runtime > Run all**, then your notes will be displayed.\n",
        "\n",
        "If you are taking the exam in person, then you must print a copy of your notes for yourself.   Here's how to print:\n",
        "* Run the cell below. \n",
        "* Click its \"Mirror cell in tab\" button (this is located in the upper right corner of the cell, immediately to the right of the trash can).  This will open the cell.  \n",
        "* In Chrome, you can then print your notes using the **File > Print** option from the browser's menu.  \n",
        "* In the print options, change the layout from Landscape to Portrait. \n",
        "* Clicking the Save, will save a PDF that you can then print.\n"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1000
        },
        "id": "T3cm1WV542_a",
        "outputId": "4ea317f6-027b-4b3e-ba79-93dddcd8aaf5"
      },
      "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": 55,
      "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 Maximum expected utility says rational agent should choose actions that maximize expected utility. MEU doesn't solve ai problem doesn't operationalize what an AI should do, just what it should do.   $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 MEU is not only rational way for agents to act (could want to minimize loss for example). 6 constraints for preference relations: Orderability (rational agent must prefer one lottery to another or like them equally), Transitivity (If like a over b and b over c, like a over c), Continuity (if b is between a and c, some probability st agent will be indifferent getting b for sure and lottery that gives a with prob p and c with prob 1 - p), subsitutability (if agent is indifferent between a and b, indifferent to two complex lotteries that are teh same except b is substituted for a in one), monotonicity (if two lotteries have same outcome, if agent prefers a to b, prefer lottery with higher chance of a occuring),\ndecomposability (compound lotteries can be reduced via laws of probability). 6 axions of utility theory. If an agent's preferences obey those 6 axioms, than a utility function exists st u(a) = u(b) if indifferent and u(a) > u(b) if prefers a.   \n\n## AIMA Chapter 16.3 Utility Functions\n Your summary here \n\n## AIMA Chapter 17.1 Sequential Decision Problems\n YActions can be unreliable (stochastic). Assume moves are markovian (only depend on current move). MDPS have actions, transition model, and reward function. Methods for solving involve dynamic programming. Solution specifies what must be done at a given state (policy). Denote by pi. Optimal policy yields best expected utility.\nOptimality of policies depends on reward. Finite horizon vs infinite horizon. Finite means after n moves, game ends. If a policy depends on time, is called nonstationary. Otherwise stationary(like hw). Rewards are additive, with a discount factor so prefers closer rewards. People prefer sooner, and sometimes award may never arrive since stochastic.\nCan compare policies by comparing expected utilities. With infinite horizon and discounted utilities, optimal policy is independent of starting state. MDPs can't be solved with a fixed number of moves. An optimal policy yields the highest expected utility. Policy is a simple reflex agent.\nInfinite horizon problems are guaranteed to be stationary (conditional prob table doesn't change over time. ). Q function gives expected value of an action in a state. Bellman equation: Assuming agent chooses best action, utility of state is the expected reward for the next transition plus the discounted utility of the next state.   \n\n## AIMA Chapter 17.2 Algorithms for MDPs\n For value iteration, have n states, so n bellman equations, don't know utilities. Calculate right hand side of equation, fill in left, eventually converge to correct value. Leads to optimal policy. Start with arbitary values, bellman update until equilibrium. Bellman update is contraction by factor of constant discount factor. Possible to get optimal policy with inaccurate utility function.\nPolicy evaulation calculates utility of each step with new policy, than new MEU policy. If meu yields no improvement, stop. For large state spaces, can skip steps, leading to modified policy evaluation. Both aforementioned policies update all states at once, not necessary. Policy evaluation is implemented by using bellman equation. Async iteration is when it only updates a subset of states. Can't solve large mdps with value/policy iteration.\n\n\n## Module 8 Lecture Notes\n Your summary here \n\n## Module 8 Definitions\n* **Utility function** - Assigns number to express state's desirability\n* **Expected utility** - Average utility over outcomes\n* **Environment history** - sequence of state and actions\n* **Markov decision process** - sequential decision problem for fully oberservable stochastic environments\n* **Proper policy** - policy guaranteed to reach terminal state\n* **Q function** - Gives expected utility of taking action in a state\n* **Bellman equation** - expected reward  for next transition + discounted utility of next state, assuming optimal action\n* **Contraction** - function of an argument that when applied to two inputs, produces two values closer together. (Divide by two)\n\n\n# Module 9: Reinforcement Learning\n## AIMA Chapter 17.3 Bandit Problems\n N armed bandit: slot machine with n levers, different prob dists. Do you pull level with best known payoff (exploitation) or the lever you haven't tried yet (exploration). One way to think of bandit problem is each arm is a mdp with one action, and entire machine is mdp. Bernoulli bandit: bandit problem where arm produces 0 or 1.\n \n\n## AIMA Chapter 22.1 Learning from Rewards\n Rewards are sparse when few states give the agent info. In reinforcement learning, agent is in MDP but not given mdp to solve (doesn't know transition/reward function.) Easier to provide reward signals than labels. Sparse rewards make learning much harder.\n1  \n\n## AIMA Chapter 22.2 Passive Reinforcement Learning\n Passive learning is like policy evaluation, however doesn't know transition model or reward function. Agent does amount of trials with a policy, keeps track of rewards received and action taken. DUE keeps average, over infinite trials would eventually converge to true expectation.\n However, ignores state connections. Adaptive dynamic programming learns transition model that connects states. Easy as model is fully observable. Direct utility estimation turns reinforcement learning into supervised learning. Ignores connection between states.   \n\n## AIMA Chapter 22.3 Active Reinforcement Learning\n Agent needs to learn transition model. Greedy agents often fail as what they think is optimal actually isn't. Should be GLIE, which must take every action some number of times. Can give weight to options not tried yet. Much faster than strictly greedy\nSome actions are irreversible and can lead to absorbing states (no actions matter/no rewards). Q learning method avoids need for model, learns q function instead.  \n\n## AIMA Chapter 22.4 Generalization in Reinforcement Learning\n In real world environments, convergence will be too slow with previous methods. Use function approximation to construct approximation of q function. Allows agent to make generalizations about states it hasn't visited. Direct utility estimations attempts to extract sum of rewards received at that state until termination.\n \n\n## Module 9 Lecture Notes\n Your summary here \n\n## Module 9 Definitions\n* **Reinforcement learning** - agent interacts with world, occasionally receiving rewards based on how it performs, doesn't need labels\n* **Model based rl** - agent uses transition model to interpret rewards and make decisions\n* **Model free rl** - No transition model, either action utlity learning (q function) or policy search(mdp)\n* **Passive rl** - policy is fixed, agent wants to learn state utilities, similar to policy evaluation, doesnt know reward/transition\n* **Active rl** - agent must figure out what to do, explore\n* **Direct utility estimation** - utility of state is defined as expected total reward from state on, each trial is a sample.\n* **Temporal difference learning** - use transitions to adjust state utilities\n* **Greedy agent** - Takes what it thinks is optimal choice at each step\n* **Reward-to-go** - total reward from a given state onward give a particular policy\n* **** - \n\n\n# Module 10: Probabilies and Language Models\n## AIMA Chapter 12.1 Acting under Uncertainty\n An agent may never know what state its in or where it will be (uncertainity). Using logic for a domain can fail for 3 reasons: Laziness, list of complete antecedents or consequents is too long, theoritical ignorance, no complete theory, practical ignorance, don't have all of the details.\nSolved by probability theory. Might not be certain, but have good idea. Agents must have preferences for outcomes (utility theory). Decision theory combines probability theory and utility theory.   \n\n## AIMA Chapter 12.2 Basic Probability Notation\n  \n\n## AIMA Chapter 12.3 Inference Using Full Joint Distributions\n  \n\n## AIMA Chapter 12.4 Independence\n Variables are independent is P(a) * P(b) = P(a and b). Bayes rule with background evidence: P(y|x, e) = P(x|y,e)P(y|e)/P(x). General form puts alpha in front of P(x|y)P(y) for product rule.\nDiagnostic info (cause|effect) more fragile than causal (effect|cause). \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 Naive bayes: P(cause, effect_1-n) = P(cause) product of P(effect_i|cause). Often used for text classification \n\n## AIMA Chapter 12.7 The Wumpus World Revisited\n Your summary here \n\n## SLP Chapter 3.1 N-Grams\n For ngrams, history isn't the best way to generate probabilities since new sentences are created often. Can use chainrule of prob, product of P(X_k|X_1-k-1). Can also approximate history using last few words (break down into bigrams). Assumption is markovian.\n \n\n## SLP Chapter 3.2 Evaluating Language Models\n  \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 Should try to make sure training and test data have similar genre (shakespeare vs wsj). Some models may also have words that occur with 0 probability even they they are possible combinations. Ok for closed vocabularies. For open vocabs, add marker called unk. Perplexity should only be compared for language models with same vocab.\n \n\n## SLP Chapter 3.5 Smoothing\n Laplace smoothing adds 1 to every count.  \n\n## SLP Chapter 3.7 Huge Language Models and Stupid Backoff\n Your summary here \n\n## Module 10 Lecture Notes\n Your summary here \n\n## Module 10 Definitions\n* **Belief state** - set of possible states the agent could be in (too large)\n* **Rational decision** - depends on relative important of goals and their likelihood of success\n* **Condition probability** - P(A|b) = P(A and B)/P(b) (bayes rule)\n* **Product rule** - p(a and b) = p(a|b)p(b)\n* **Marginal probability** - unconditional probability\n* **Extrinsic evaluation** - embed language model in application, see if it improves (expensive)\n* **Intrinsic evaluation** - measures independent of application\n* **Perplexity** - Used to evaluate models, weighted average branching factor of a language. More info = less perplexity\n* **Smoothing** - allocate probability from frequently seen occurences to never seen occurences\n* **** - \n\n\n# Module 11: Probabilistic Reasoning and Bayes’ Nets\n## AIMA Chapter 13.1 Representing Knowledge in an Uncertain Domain\n Bayesian networks can in effect represent the dependence among variables, and even any full joint prob distribution. Bayes nets are directed graphs, each node is random variable, if edge from x to y x is parent, each node has probability x given its parents, which helps show the effect of parents on the node.\n\n\n## AIMA Chapter 13.2 The Semantics of Bayesian Networks\n To construct bayes net, set nodes, label 1-n, set appropriate edges (minimal, parents). Parents should be nodes that have direct influence on node. This guarantees acyclic. Bayes can be more compact than full joint dist.\nSparse/locally structured system, linear. Must choose node ordering well. In bayes nets, variables are conditionally independent on non descendants, and conditionally independent of all nodes in the network given its parents, childrens, children's parents, its markov blanket. \nD separation of x, y, z- consider subgraph of x, y, z, and ancestors, add links between unlinked nodes that have a common child, replace directed with undirected, if z blocks all paths between x and y, z d separates x and y. If so, x conditionally independent of y.\n A way to handle continuous variables is discretization of variables. Loss of accuracy, slower. Also can use probability density function, \n\n## AIMA 13.3 Exact Inference in Bayesian Networks\n  \n\n## Module 11 Lecture Notes\n Your summary here \n\n## Module 11 Definitions\n* **Chain rule** - P(X_i|X_1-i-1) = P(X_i|Parents(X_i))\n* **Determinisitic node** - node's value is determined by its parents\n\n\n# Module 12: Naive Bayes and Perceptrons\n## AIMA Chapter 5.1 Game Theory\n Three main types of learning: supervised learning, agent learns, predicts labels for actions. Unsupervised learning, learns inputs without explicit feedback, reinforcement learning, agent learns from reinforcement. \n \n\n## AIMA Chapter 5.2 Optimal Decisions in Games\n Can analyze hypothesis space by its bias. True to trade off between bias and variances. Linear has lots of bias. \n\n## AIMA Chapter 5.3 Heuristic Alpha–Beta Tree Search\n Learn decision tree algo: start with most important problem, recursively solve smaller subproblems. Can skip some features if they aren't relevant to the solution. Can evaluate performance with learning curve, proportion of correct over training set size.\nMore attributes means overfitting is more likely. To combat overfitting, use decision tree pruning, prune irrelevant nodes.   \n\n## AIMA Chapter 5.5 Stochastic Games\n  \n\n## AIMA Chapter 16.1 Combining Beliefs and Desires under Uncertainty\n  \n\n## AIMA Chapter 16.2 The Basis of Utility Theory\n \n\n## SLP Chapter 4.1 Naive Bayes Classifiers\n Bag of words representation only keeps the frequency of words in a doc. Another naive bayes assumption is that the probability of features given a class are independent. Called a linear classifier \n\n## SLP Chapter 4.2 Training the Naive Bayes Classifier\n With naive bayes, can use frequencies in data to learn probabilities. Can use laplace smoothing in case of zero probabilties since they are all multiplied together. We also ignore unknown words. Can also ignore stop words. \n\n## SLP Chapter 4.3 Worked Example\n   \n\n## SLP Chapter 4.4 Optimizing for Sentiment Analysis\n  \n\n## SLP Chapter 4.5 Naive Bayes for other text classification tasks\n  \n\n## SLP Chapter 4.6 Naive Bayes as a Language Model\n  \n\n## SLP Chapter 4.7 Evaluation: Precision, Recall, F-measure\n \n\n## SLP Chapter 4.8 Test sets and Cross-validation\n \n\n## SLP Chapter 4.9 Statistical Significance Testing\n  \n\n## SLP Chapter 4.10 Avoiding Harms in Classification\n \n\n## Module 12 Lecture Notes\n Perceptrons use error driven learning. Takes in inputs, multiplies them by weight, takes sum, use as input to activation function. Perceptrons try to learn the weight vector. Inputs are features we want to classify. \nInputs are fixed, can only change weight. To learn weights, classify with current weights. If correct, no change, otherwise, adjust weight. \n\n## Module 12 Definitions\n* **Bias** - deviation from expected value\n* **Decision tree** - maps inputs to single output\n* **** - \n\n\n# Module 13: Neural Networks\n## SLP Chapter 5.1 Classification: the sigmoid\n Map output of regression to sigmoid function to give real valued output. Sigmoid makes it so z is between 0 and 1. If sigmoid returns .5 or greater, 1, else 0. Naive Bayes has very strong conditional independence assumptions, where as logisitic regression does not.\n   \n\n## SLP Chapter 5.2 Learning in Logistic Regression\n Need loss/cost function/ gradient function. \n\n## SLP Chapter 5.3 The cross-entropy loss function\n Use conditional maximum likelihood estimation, choose w and b to maximize log probability of the correct y labels in the training data. Resulting loss function is negative log likelihood loss, called cross-entropy loss.  \n\n## SLP Chapter 5.4 Gradient Descent\n Gradient descent goal is to find optimal weights/minimize loss function. Finds direction slop rises in most steeply, and goes in the opposite direction. This is convex for logistic regression \n\n## SLP Chapter 5.5 Regularization\n  \n\n## SLP Chapter 5.6 Multinomial logistic regression\n  \n\n## SLP Chapter 7.1 Units\n Neural networks are similar to logistical regression, but are more powerful (only need one layer to learn any function). Instead of handderived features, take raw words as inputs. Computational unit takes weighted sum of inputs + bias.\nOntop of sigmoid, also have ReLU, which is max(z, 0). Also tanh. (e^z-e^-z)/(e^z+e^-z). Tanh is smoothly differentiable, maps outliers towards mean. ReLU is nearly linear, prevents derivatives from being close to 0, which we want. \n\n## SLP Chapter 7.2 The XOR problem\n A single perceptron can't computer xor. Means xor is not linearly separable. Xor can be calculated by a \"layered network of units\".  \n\n## SLP Chapter 7.3 Feedforward Neural Networks\n Feedforward network is a network with no cycles, multi layered, outputs pass to next layer, cant pass back. Not made of perceptrons anymore. Layers are fully connected, so each unit takes input from all units in previous layer.\n \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 To train a neural net, need loss function (cross entropy loss). Need to know gradient of loss function. Computed via error backpropagation. \n\n## SLP Chapter 7.7 Training the neural language model\n Your summary here \n\n## Module 13 Lecture Notes\n ML classifiers have a feature representation, classification function, objective function (how good algo is), and an optimization algo. Logistic regression learns weight for each input and a bias term. \nDifference from perceptron is range of outputs. To get the weights use loss function that tells us distance between system output and gold output, and algo to minimize loss function (how much output differs from correct output).\nNeural network built of many logistic regressions (not perceptrons?). Out is put through sigmoid function, makes updating weight easier. Generally just computational units. To train neural networks, need loss function, optimization algo,\nand a way of computing gradient of a loss function. error Backpropagatiion algo helps calculate gradient for all layers. yy  \n\n## Module 13 Definitions\n* **Concept** - definition\n\n\n# Module 14: Natural Language Processing\n## SLP Chapter 9.1 Language Models Revisited\n  \n\n## SLP Chapter 9.2 Recurrent Neural Networks\n  a recurrent neural network contains cycles. \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 Vector semantics main idea is to represent a word as a point in space that is derived from the distribution of its neighbors. Word vectors are called embeddings. Two main models: tf-idf, based on nearby word count, and word2vec, which produce dense(tf-idf is sprase) vectors with semantic properties.\n \n\n## SLP Chapter 6.3 Words and Vectors\n In term doc matrix, row represents word, column represents a document. Cell is how many times word appeared in doc. Information retrieval is trying to find the document that best matches the query.  \n\n## SLP Chapter 6.4 Cosine for measuring similarity\n To measure similiarity of two word vectors, take cosine of the angle between them. Raw dot product favors longer vectors. To solve this we normalize the dot product. \n\n## SLP Chapter 6.8 Word2vec\n Embeddings are short dense vectors. Work better in every nlp task than sparse vectors. One way of computing embeddings is skip gram with negative sampling. Don't count how often word x appears near word y, but train \"is x likely to appear near y? Essentially self supervision.\nSkipgram: treat target word and neighbor as positive examples, randomly sample other words to get negative sample, use logistic regression to train classifier on two cases, use learned weights as embeddings.\n \n\n## SLP Chapter 6.10 Semantic properties of embeddings\n  \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 ML classifiers have a feature representation, classification function, objective function (how good algo is), and an optimization algo. Logistic regression learns weight for each input and a bias term. \nDifference from perceptron is range of outputs. To get the weights use loss function that tells us distance between system output and gold output, and algo to minimize loss function (how much output differs from correct output).\nNeural network built of many logistic regressions (not perceptrons?). Out is put through sigmoid function, makes updating weight easier. Generally just computational units. To train neural networks, need loss function, optimization algo,\nand a way of computing gradient of a loss function. error Backpropagatiion algo helps calculate gradient for all layers. yy  \n\n## Module 14 Definitions\n* **Concept** - definition\n",
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {}
        }
      ]
    }
  ]
}