{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# CSC338. Homework 6\n",
    "\n",
    "Due Date: Wednesday March 4, 9pm\n",
    "\n",
    "Please see the guidelines at https://www.cs.toronto.edu/~lczhang/338/homework.html\n",
    "\n",
    "### What to Hand In\n",
    "\n",
    "Please hand in 2 files:\n",
    "\n",
    "- Python File containing all your code, named `hw6.py`.\n",
    "- PDF file named `hw6_written.pdf` containing your solutions to the written parts of the assignment. Your solution can be hand-written, but must be legible. Graders may deduct marks for illegible or poorly presented solutions.\n",
    "\n",
    "If you are using Jupyter Notebook to complete the work, your notebook can be exported as a .py file (File -> Download As -> Python). Your code will be auto-graded using Python 3.6, so please make sure that your code runs. There will be a 20% penalty if you need a remark due to small issues that renders your code untestable.\n",
    "\n",
    "**Make sure to remove or comment out all matplotlib or other expensive code before submitting your homework!**\n",
    "\n",
    "Submit the assignment on **MarkUs** by 9pm on the due date. See the syllabus for the course policy regarding late assignments. All assignments must be done individually."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import math\n",
    "import numpy as np"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Question 1\n",
    "\n",
    "### Part (a) -- 3 pt\n",
    "\n",
    "Write a function `solve_normal_equation` that takes an $m \\times n$ matrix $A$ (with $m > n$ and \n",
    "$rank(A) = n$) and a vector $b$,\n",
    "and solves the linear least squares problem $A x \\approx b$ using the Normal Equation method.\n",
    "\n",
    "Use the `cholesky_factorize` method and other methods that you wrote in previous\n",
    "homeworks, but do not use any functions from the package `np.linalg`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def solve_normal_equation(A, b):\n",
    "    \"\"\"\n",
    "    Return the solution x to the linear least squares problem\n",
    "        $$Ax \\approx b$$ using normal equations,\n",
    "    where A is an (m x n) matrix, with m > n, rank(A) = n, and\n",
    "          b is a vector of size (m)\n",
    "    \"\"\""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Part (b) -- 1 pt\n",
    "\n",
    "Consider the linear least square system below, where $A$ is a $50 \\times 3$ matrix,\n",
    "and $b$ is a vector of size $50$. The system is derived from the \"iris\" dataset.\n",
    "\n",
    "Use the `solve_normal_equation` function you wrote in part (a) to find the vector `x`\n",
    "that minimizes the norm of `matmul(A, x) - b`.\n",
    "\n",
    "Store the solution in the variable `iris_x` and the 2-norm of the residual\n",
    "in `iris_residual`. You may use the function `np.linalg.norm`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "irisA = np.array([[4.8, 6.3, 5.7, 5.1, 7.7, 5.6, 4.9, 4.4, 6.4, 6.2, 6.7, 4.5, 6.3,\n",
    "                   4.8, 5.8, 4.7, 5.4, 7.4, 6.4, 6.3, 5.1, 5.7, 6.5, 5.5, 7.2, 6.9,\n",
    "                   6.8, 6. , 5. , 5.4, 5.6, 6.1, 5.9, 5.6, 6. , 6. , 4.4, 6.9, 6.7,\n",
    "                   5.1, 6. , 6.3, 4.6, 6.7, 5. , 6.7, 5.8, 5.1, 5.2, 6.1],\n",
    "                  [3.1, 2.5, 3. , 3.7, 3.8, 3. , 3.1, 2.9, 2.9, 2.9, 3.1, 2.3, 2.5,\n",
    "                   3.4, 2.7, 3.2, 3.7, 2.8, 2.8, 3.3, 2.5, 4.4, 3. , 2.6, 3.2, 3.2,\n",
    "                   3. , 2.9, 3.6, 3.9, 3. , 2.6, 3.2, 2.8, 2.7, 2.2, 3.2, 3.1, 3.1,\n",
    "                   3.8, 2.2, 2.7, 3.1, 3. , 3.5, 2.5, 4. , 3.5, 3.4, 3. ],\n",
    "                  [1.6, 4.9, 4.2, 1.5, 6.7, 4.5, 1.5, 1.4, 4.3, 4.3, 5.6, 1.3, 5. ,\n",
    "                   1.6, 5.1, 1.3, 1.5, 6.1, 5.6, 6. , 3. , 1.5, 5.8, 4.4, 6. , 5.7,\n",
    "                   5.5, 4.5, 1.4, 1.3, 4.1, 5.6, 4.8, 4.9, 5.1, 5. , 1.3, 4.9, 4.4,\n",
    "                   1.5, 4. , 4.9, 1.5, 5.2, 1.3, 5.8, 1.2, 1.4, 1.4, 4.9]])\n",
    "irisb = np.array([0.2, 1.5, 1.2, 0.4, 2.2, 1.5, 0.1, 0.2, 1.3, 1.3, 2.4, 0.3, 1.9,\n",
    "                  0.2, 1.9, 0.2, 0.2, 1.9, 2.1, 2.5, 1.1, 0.4, 2.2, 1.2, 1.8, 2.3,\n",
    "                  2.1, 1.5, 0.2, 0.4, 1.3, 1.4, 1.8, 2. , 1.6, 1.5, 0.2, 1.5, 1.4,\n",
    "                  0.3, 1. , 1.8, 0.2, 2.3, 0.3, 1.8, 0.2, 0.2, 0.2, 1.8])\n",
    "A = irisA.T # transpose\n",
    "b = irisb\n",
    "\n",
    "iris_x = None\n",
    "iris_residual = None"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Question 2\n",
    "\n",
    "### Part (a) -- 3 pt\n",
    "\n",
    "Write a function `householder_v` that returns the vector $v$ that defines\n",
    "the Householder transform\n",
    "\n",
    "$$H = I - 2 \\frac{v v^T} {v^T v}$$\n",
    "\n",
    "that eliminates all but the first element of a vector $a$.\n",
    "You may use the function `np.linalg.norm`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def householder_v(a):\n",
    "    \"\"\"Return the vector $v$ that defines the Householder Transform\n",
    "         H = I - 2 np.matmul(v, v.T) / np.matmul(v.T, v)\n",
    "    that will eliminate all but the first element of the \n",
    "    input vector a. Choose the $v$ that does not result in\n",
    "    cancellation.\n",
    "\n",
    "    Do not modify the vector `a`.\n",
    "    \n",
    "    Example:\n",
    "        >>> a = np.array([2., 1., 2.])\n",
    "        >>> householder_v(a)\n",
    "        array([5., 1., 2.])\n",
    "        >>> a\n",
    "        array([2., 1., 2.])\n",
    "    \"\"\""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Part (b) -- 2 pt\n",
    "\n",
    "Show that a Householder Transformation $H$ is orthogonal.\n",
    "Include your solution in your PDF writeup.\n",
    "\n",
    "### Part (c) -- 2 pt\n",
    "\n",
    "Write a function `apply_householder` that applies the Householder\n",
    "transform defined by a vector $v$ to a vector $u$. You should **not**\n",
    "compute the Householder transform matrix $H$. You should only \n",
    "need to compute vector-vector dot products and vector-scalar multiplications."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def apply_householder(v, u):\n",
    "    \"\"\"Return the result of the Householder transformation defined\n",
    "    by the vector $v$ applied to the vector $u$. You should not\n",
    "    compute the Householder matrix H directly.\n",
    "    \n",
    "    Example:\n",
    "    \n",
    "    >>> apply_householder(np.array([5., 1., 2.]), np.array([2., 1., 2.]))\n",
    "    array([-3.,  0.,  0.])\n",
    "    >>> apply_householder(np.array([5., 1., 2.]), np.array([2., 3., 4.]))\n",
    "    array([-5. ,  1.6,  1.2])\n",
    "    \"\"\""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Part (d) -- 3 pt\n",
    "\n",
    "Write a function `apply_householder_matrix` that applies the Householder\n",
    "transform defined by a vector $v$ to all the columns of a matrix $U$. \n",
    "You should **not** compute the Householder transform matrix $H$. \n",
    "\n",
    "**Do not use for loops.** Instead, you may find the numpy function `np.outer` useful."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def apply_householder_matrix(v, U):\n",
    "    \"\"\"Return the result of the Householder transformation defined\n",
    "    by the vector $v$ applied to all the vectors in the matrix U.\n",
    "    You should not compute the Householder matrix H directly.\n",
    "    \n",
    "    Example:\n",
    "    \n",
    "    >>> v = np.array([5., 1., 2.])\n",
    "    >>> U = np.array([[2., 2.],\n",
    "                      [1., 3.], \n",
    "                      [2., 4.]])\n",
    "    >>> apply_householder_matrix(v, U)\n",
    "    array([[-3. , -5. ],\n",
    "           [ 0. ,  1.6],\n",
    "           [ 0. ,  1.2]])\n",
    "    \"\"\""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Part (e) -- 3 pt\n",
    "\n",
    "Write a function `solve_qr_householder` that takes an $m \\times n$ matrix $A$ and a vector $b$,\n",
    "and solves the linear least squares problem $A x \\approx b$ using Householder QR Factorization.\n",
    "You may use `np.linalg.solve` to solve any square system of the form $Ax = b$ that you produce.\n",
    "\n",
    "You should use the helper function `qr_householder` that takes a matrix A and a vector b and\n",
    "performs the Householder QR Factorization using the functions you wrote in parts (b-d)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def qr_householder(A, b):\n",
    "    \"\"\"Return the matrix [R O]^T, and vector [c1 c2]^T equivalent\n",
    "    to the system $Ax \\approx b$. This algorithm is similar to\n",
    "    Algorithm 3.1 in the textbook.\n",
    "    \"\"\"\n",
    "    for k in range(A.shape[1]):\n",
    "        v = householder_v(A[k:, k])\n",
    "        if np.linalg.norm(v) != 0:\n",
    "            A[k:, k:] = apply_householder_matrix(v, A[k:, k:])\n",
    "            b[k:] = apply_householder(v, b[k:])\n",
    "    # now, A is upper-triangular\n",
    "    return A, b\n",
    "\n",
    "def solve_qr_householder(A, b):\n",
    "    \"\"\"\n",
    "    Return the solution x to the linear least squares problem\n",
    "        $$Ax \\approx b$$ using Householder QR decomposition.\n",
    "    Where A is an (m x n) matrix, with m > n, rank(A) = n, and\n",
    "          b is a vector of size (m)\n",
    "    \"\"\""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Question 3\n",
    "\n",
    "For the next few questions, we will use the MNIST dataset for digit recognition\n",
    "Download the files `mnist_images.npy` and `mnist_labels.npy` from the course\n",
    "website, and place them into the same folder as your ipynb file.\n",
    "\n",
    "The code below loads the data, splits it into \"train\" and \"test\" sets,\n",
    "and plots the a subset of the data. We will use `train_images` and `train_labels`\n",
    "to set up Linear Least Squares problems. We will use `test_images` and `test_labels`\n",
    "to test the models that we build."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "mnist_images = np.load(\"mnist_images.npy\")\n",
    "test_images = mnist_images[4500:]  #  500 images\n",
    "train_images = mnist_images[:4500] # 4500 images\n",
    "mnist_labels = np.load(\"mnist_labels.npy\")\n",
    "test_labels = mnist_labels[4500:]\n",
    "train_labels = mnist_labels[:4500]\n",
    "\n",
    "def plot_mnist(remove_border=False):\n",
    "    \"\"\" Plot the first 40 data points in the MNIST train_images. \"\"\"\n",
    "    import matplotlib.pyplot as plt\n",
    "    plt.figure(figsize=(10, 5))\n",
    "    for i in range(4 * 10):\n",
    "        plt.subplot(4, 10, i+1)\n",
    "        if remove_border:\n",
    "            plt.imshow(train_images[i,4:24,4:24])\n",
    "        else:\n",
    "            plt.imshow(train_images[i])# plot_mnist() # please comment out this line before submission"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Part (a) -- 1 pt\n",
    "\n",
    "How many examples of each digit are in `train_images`? You should use the\n",
    "information in `train_labels`. \n",
    "\n",
    "Some of the code in the later part of this\n",
    "question might be helpful. You might also find the `sum` function helpful.\n",
    "\n",
    "Save your result in the array `mnist_digits`, where \n",
    "`mnist_digits[0]` should contain the number of digit `0` in `train_images`, \n",
    "`mnist_digits[1]` should contain the number of digit `1` in `train_images`, etc."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "mnist_digits = []"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Part (b) -- 2 pt\n",
    "\n",
    "We will build a rudimentary model to predict whether a digit is the\n",
    "digit `0`. Our features will be the intensity at each pixel.\n",
    "There are 28 * 28 = 784 pixels in each image. However, in order\n",
    "to obtain a matrix $A$ that is of full rank, we will ignore the\n",
    "pixels along the border. That is, we will only use 400 pixels\n",
    "in the center of the image.\n",
    "\n",
    "Look at a few of the MNIST images using the `plot_mnist` function\n",
    "written for you. Why would our matrix $A$ not be full rank if we \n",
    "use all 784 pixels in our model?\n",
    "\n",
    "If this question doesn't make sense yet, you might want to\n",
    "come back to it after completing the rest of this question. \n",
    "\n",
    "Include your solution in your PDF writeup."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Plot the MNIST images, with only the center pixels that we will use\n",
    "# in our digit classification model.\n",
    "#plot_mnist(True) # please comment out this line before submission"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Part (c) -- 1 pt\n",
    "\n",
    "We will now build a rudimentary model to predict whether a digit is the\n",
    "digit `0`. To obtain a matrix of full rank, we will use the 400 pixels\n",
    "at the center of each image as features. Our target will\n",
    "be whether our digit is `0`.\n",
    "\n",
    "In short, the model we will build looks like this:\n",
    "\n",
    "$$x_1 p_1 + x_2 p_2 + ... + x_{400} p_{400} = y$$\n",
    "\n",
    "Where $p_i$ is the pixel intensity at pixel $i$ (the ordering of the pixel's\n",
    "doesn't actually matter), and the value of $y$ determines whether our digit is a `0` or not.\n",
    "\n",
    "We will solve for the coefficients $x_i$ by solving the linear\n",
    "least squares problem $Ax \\approx b$, where $A$ is constructed using\n",
    "the pixel intensities of the images in `train_images`, and $y$ is constructed\n",
    "using the labels for those images. For convenience, we will set $y = 1$ for\n",
    "images of the digit `0`, and $y=0$ for other digits.\n",
    "\n",
    "**We should stress that in real machine learning courses,\n",
    "you will learn that this is not the proper way to build a digit detector.**\n",
    "However, digit detection is quite fun, so we might as well use to tools\n",
    "that we have to try and solve the problem.\n",
    "\n",
    "The code below obtains the matrices $A$ and the vector $b$ of our least squares\n",
    "problem, where $A$ is a $m \\times n$ matrix and $b$ is a vector of length $m$.\n",
    "\n",
    "What is the value of $m$ and $n$? Save the values in the variables `mnist_m` and `mnist_n`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "A = train_images[:, 4:24, 4:24].reshape([-1, 20*20])\n",
    "b = (train_labels == 0).astype(np.float32)\n",
    "\n",
    "mnist_m = None\n",
    "mnist_n = None"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Part (d) -- 1 pt\n",
    "\n",
    "Use the Householder QR decomposition method to solve the system.\n",
    "Save the result in the variable `mnist_x`.\n",
    "Save the norm of the residuals of this solution in the variable `mnist_r`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "mnist_x = None\n",
    "mnist_r = None"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Part (e) -- 1 pt\n",
    "\n",
    "Consider `test_images[0]`. Is this image of the digit 0? Set the value of `test_image_0` to either `True` or `False`\n",
    "depending on your result.\n",
    "\n",
    "Let $p$ be the vector containing the values of the 400 center pixels in `test_image[0]`. The features are extracted\n",
    "for you in the variabel `p`. Use the solution `mnist_x` to estimate the target $y$ for the vector $p$.\n",
    "Save the (float) value of the predicted value of $y$ in the variable `test_image_0_y`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# import matplotlib.pyplot as plt # Please comment before submitting\n",
    "# plt.imshow(test_images[0]) # Please comment before submitting\n",
    "p = test_images[0, 4:24, 4:24].reshape([-1, 20*20])\n",
    "test_image_0 = None\n",
    "test_image_0_y = None"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Part (f) -- 2 pt\n",
    "\n",
    "Write code to predict the value of $y$ for **every** image in `test_images`. Save\n",
    "your result in `test_image_y`.\n",
    "\n",
    "**Do not use a loop.**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "test_image_y = None"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Part (g) -- 1 pt\n",
    "\n",
    "We will want to turn the continuous estimates of $y$ into discrete predictions\n",
    "about whether an image is of the digit 0.\n",
    "\n",
    "We will do this by selecting a **cutoff**. That is, we will predict that\n",
    "a test image is of the digit 0 if the prediction $y$ for that digit is at least $0.5$.\n",
    "\n",
    "Create a numpy array `test_image_pred` with `test_image_pred[i] == 1` if `test_image[i]`\n",
    "is of the digit 0, and `test_image_pred[i] == 0` otherwise. Then, run\n",
    "the code to compute the `test_accuracy`, or the portion of the times that\n",
    "our prediction matches the actual label.\n",
    "\n",
    "HINT: You might find the code in Part(c) helpful.\n",
    "\n",
    "(This is somewhat of an arbitrary cutoff. You will learn the proper way\n",
    " to do this prediction problem in a machine learning course like\n",
    " CSC411 or CSC321.)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "test_image_pred = None\n",
    "# test_accuracy = sum(test_image_pred == (test_labels == 0).astype(float)) / len(test_labels)\n",
    "# print(test_accuracy)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Part (h) -- 4 pt\n",
    "\n",
    "So far, we built a linear least squares model that determines whether an image is of the digit 0.\n",
    "Let's go a step further, and build such a model for **every** digit!\n",
    "\n",
    "Complete the function `mnist_classifiers` that uses `train_images` and `train_labels`,\n",
    "and uses the function `solve_normal_equation` to build a linear least squares model for\n",
    "every digit. The function should return a matrix $xs$ of shape $10 \\times 400$,\n",
    "with `xs[0] == mnist_x1` from earlier.\n",
    "\n",
    "**Make sure to comment out any code you use to test `mnist_classifier`, or your code might not be testable.**\n",
    "\n",
    "This part of the code will be graded by your TA."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def mnist_classifiers():\n",
    "    \"\"\"Return the coefficients for linear least squares models for every digit.\n",
    "    \n",
    "    Example:\n",
    "        >>> xs = mnist_classifiers()\n",
    "        >>> np.all(xs[0] == mnist_x1)\n",
    "        True\n",
    "    \"\"\"\n",
    "    # you can use train_images and train_labels here, and make\n",
    "    # whatever edits to this function as you wish.\n",
    "    A = train_images[:, 4:24, 4:24].reshape([-1, 20*20])\n",
    "    xs = []\n",
    "    # ...\n",
    "    return np.stack(xs)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Just for fun...\n",
    "\n",
    "The code below makes predictions based on the result of your `mnist_classifier`.\n",
    "That is, for every test image, the code runs all 10 models to see whether the\n",
    "test image contains each of the 10 digits. We make a discrete prediction about\n",
    "which digit the image contains by looking at which model yields the **largest**\n",
    "value of $y$ for the image.\n",
    "\n",
    "The code then compares the result against the actual labels, computes the\n",
    "accuracy measure: the fraction of predictions that is correct. Just for fun,\n",
    "look at the prediction accuracy of our model, but please comment any code you\n",
    "write before submitting your assignment.\n",
    "\n",
    "Again, in machine learning and statistics courses you will learn \n",
    "ways to classifying digits that are better and more principled.\n",
    "You'll achieve a much better test accuracy than what we have here."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def prediction_accuracy(xs):\n",
    "    \"\"\"Return the prediction \n",
    "    \"\"\"\n",
    "    testA = test_images[:, 4:24, 4:24].reshape([-1, 20*20])\n",
    "    ys = np.matmul(testA, xs.T)\n",
    "    pred = np.argmax(ys, axis=1)\n",
    "    return sum(pred == test_labels) / len(test_labels)"
   ]
  }
 ],
 "metadata": {},
 "nbformat": 4,
 "nbformat_minor": 2
}
