{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "dzNng6vCL9eP"
   },
   "source": [
    "## CS231n Python Tutorial With Jupyter Notebook"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "0vJLt3JRL9eR"
   },
   "source": [
    "This tutorial was originally written by [Justin Johnson](https://web.eecs.umich.edu/~justincj/) for cs231n and adapted as a Jupyter notebook for cs228 by [Volodymyr Kuleshov](http://web.stanford.edu/~kuleshov/) and [Isaac Caswell](https://symsys.stanford.edu/viewing/symsysaffiliate/21335).\n",
    "\n",
    "This current version has been adapted as a Jupyter notebook with Python3 support by Kevin Zakka for the Spring 2020 edition of [cs231n](http://cs231n.stanford.edu/)."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "fY12nHhyL9hX"
   },
   "source": [
    "Numpy is the core library for scientific computing in Python. It provides a high-performance multidimensional array object, and tools for working with these arrays. If you are already familiar with MATLAB, you might find this [tutorial](http://wiki.scipy.org/NumPy_for_Matlab_Users) useful to get started with Numpy."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "lZMyAdqhL9hY"
   },
   "source": [
    "To use Numpy, we first need to import the `numpy` package:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "58QdX8BLL9hZ"
   },
   "outputs": [],
   "source": [
    "import numpy as np"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "DDx6v1EdL9hb"
   },
   "source": [
    "### Arrays"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "f-Zv3f7LL9hc"
   },
   "source": [
    "A numpy array is a grid of values, all of the same type, and is indexed by a tuple of nonnegative integers. The number of dimensions is the rank of the array; the shape of an array is a tuple of integers giving the size of the array along each dimension."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "_eMTRnZRL9hc"
   },
   "source": [
    "We can initialize numpy arrays from nested Python lists, and access elements using square brackets:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 52
    },
    "colab_type": "code",
    "id": "-l3JrGxCL9hc",
    "outputId": "8d9dad18-c734-4a8a-ca8c-44060a40fb79"
   },
   "outputs": [],
   "source": [
    "a = np.array([1, 2, 3])  # Create a rank 1 array\n",
    "print(type(a), a.shape, a[0], a[1], a[2])\n",
    "a[0] = 45                 # Change an element of the array\n",
    "print(a)                  "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 52
    },
    "colab_type": "code",
    "id": "ma6mk-kdL9hh",
    "outputId": "0b54ff2f-e7f1-4b30-c653-9bf81cb8fbb0"
   },
   "outputs": [],
   "source": [
    "b = np.array([[1,2,3],[4,5,6]])   # Create a rank 2 array\n",
    "print(b)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 52
    },
    "colab_type": "code",
    "id": "ymfSHAwtL9hj",
    "outputId": "5bd292d8-c751-43b9-d480-f357dde52342"
   },
   "outputs": [],
   "source": [
    "print(b.shape)\n",
    "print(b[0, 0], b[0, 1], b[1, 0])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "F2qwdyvuL9hn"
   },
   "source": [
    "Numpy also provides many functions to create arrays:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 52
    },
    "colab_type": "code",
    "id": "mVTN_EBqL9hn",
    "outputId": "d267c65f-ba90-4043-cedb-f468ab1bcc5d"
   },
   "outputs": [],
   "source": [
    "a = np.zeros((2,2))  # Create an array of all zeros\n",
    "print(a)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 34
    },
    "colab_type": "code",
    "id": "skiKlNmlL9h5",
    "outputId": "7d1ec1b5-a1fe-4f44-cbe3-cdeacad425f1"
   },
   "outputs": [],
   "source": [
    "b = np.ones((1,2))   # Create an array of all ones\n",
    "print(b)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 52
    },
    "colab_type": "code",
    "id": "HtFsr03bL9h7",
    "outputId": "2688b157-2fad-4fc6-f20b-8633207f0326"
   },
   "outputs": [],
   "source": [
    "c = np.full((2,2), 7) # Create a constant array\n",
    "print(c)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 52
    },
    "colab_type": "code",
    "id": "-QcALHvkL9h9",
    "outputId": "5035d6fe-cb7e-4222-c972-55fe23c9d4c0"
   },
   "outputs": [],
   "source": [
    "d = np.eye(2)        # Create a 2x2 identity matrix\n",
    "print(d)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 52
    },
    "colab_type": "code",
    "id": "RCpaYg9qL9iA",
    "outputId": "25f0b387-39cf-42f3-8701-de860cc75e2e"
   },
   "outputs": [],
   "source": [
    "e = np.random.random((2,2)) # Create an array filled with random values\n",
    "print(e)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "jI5qcSDfL9iC"
   },
   "source": [
    "### Array indexing"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "M-E4MUeVL9iC"
   },
   "source": [
    "Numpy offers several ways to index into arrays."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "QYv4JyIEL9iD"
   },
   "source": [
    "Slicing: Similar to Python lists, numpy arrays can be sliced. Since arrays may be multidimensional, you must specify a slice for each dimension of the array:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 52
    },
    "colab_type": "code",
    "id": "wLWA0udwL9iD",
    "outputId": "99f08618-c513-4982-8982-b146fc72dab3"
   },
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "# Create the following rank 2 array with shape (3, 4)\n",
    "# [[ 1  2  3  4]\n",
    "#  [ 5  6  7  8]\n",
    "#  [ 9 10 11 12]]\n",
    "a = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]])\n",
    "\n",
    "# Use slicing to pull out the subarray consisting of the first 2 rows\n",
    "# and columns 1 and 2; b is the following array of shape (2, 2):\n",
    "# [[2 3]\n",
    "#  [6 7]]\n",
    "b = a[:2, 1:3]\n",
    "print(b)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "KahhtZKYL9iF"
   },
   "source": [
    "A slice of an array is a view into the same data, so modifying it will modify the original array."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 52
    },
    "colab_type": "code",
    "id": "1kmtaFHuL9iG",
    "outputId": "ee3ab60c-4064-4a9e-b04c-453d3955f1d1"
   },
   "outputs": [],
   "source": [
    "print(a[0, 1])\n",
    "b[0, 0] = 77    # b[0, 0] is the same piece of data as a[0, 1]\n",
    "print(a[0, 1]) "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "_Zcf3zi-L9iI"
   },
   "source": [
    "You can also mix integer indexing with slice indexing. However, doing so will yield an array of lower rank than the original array. Note that this is quite different from the way that MATLAB handles array slicing:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 69
    },
    "colab_type": "code",
    "id": "G6lfbPuxL9iJ",
    "outputId": "a225fe9d-2a29-4e14-a243-2b7d583bd4bc"
   },
   "outputs": [],
   "source": [
    "# Create the following rank 2 array with shape (3, 4)\n",
    "a = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]])\n",
    "print(a)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "NCye3NXhL9iL"
   },
   "source": [
    "Two ways of accessing the data in the middle row of the array.\n",
    "Mixing integer indexing with slices yields an array of lower rank,\n",
    "while using only slices yields an array of the same rank as the\n",
    "original array:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 69
    },
    "colab_type": "code",
    "id": "EOiEMsmNL9iL",
    "outputId": "ab2ebe48-9002-45a8-9462-fd490b467f40"
   },
   "outputs": [],
   "source": [
    "row_r1 = a[1, :]    # Rank 1 view of the second row of a  \n",
    "row_r2 = a[1:2, :]  # Rank 2 view of the second row of a\n",
    "row_r3 = a[[1], :]  # Rank 2 view of the second row of a\n",
    "print(row_r1, row_r1.shape)\n",
    "print(row_r2, row_r2.shape)\n",
    "print(row_r3, row_r3.shape)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 104
    },
    "colab_type": "code",
    "id": "JXu73pfDL9iN",
    "outputId": "6c589b85-e9b0-4c13-a39d-4cd9fb2f41ac"
   },
   "outputs": [],
   "source": [
    "# We can make the same distinction when accessing columns of an array:\n",
    "col_r1 = a[:, 1]\n",
    "col_r2 = a[:, 1:2]\n",
    "print(col_r1, col_r1.shape)\n",
    "print()\n",
    "print(col_r2, col_r2.shape)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "VP3916bOL9iP"
   },
   "source": [
    "Integer array indexing: When you index into numpy arrays using slicing, the resulting array view will always be a subarray of the original array. In contrast, integer array indexing allows you to construct arbitrary arrays using the data from another array. Here is an example:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 52
    },
    "colab_type": "code",
    "id": "TBnWonIDL9iP",
    "outputId": "c29fa2cd-234e-4765-c70a-6889acc63573"
   },
   "outputs": [],
   "source": [
    "a = np.array([[1,2], [3, 4], [5, 6]])\n",
    "\n",
    "# An example of integer array indexing.\n",
    "# The returned array will have shape (3,) and \n",
    "print(a[[0, 1, 2], [0, 1, 0]])\n",
    "\n",
    "# The above example of integer array indexing is equivalent to this:\n",
    "print(np.array([a[0, 0], a[1, 1], a[2, 0]]))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 52
    },
    "colab_type": "code",
    "id": "n7vuati-L9iR",
    "outputId": "c3e9ba14-f66e-4202-999e-2e1aed5bd631"
   },
   "outputs": [],
   "source": [
    "# When using integer array indexing, you can reuse the same\n",
    "# element from the source array:\n",
    "print(a[[0, 0], [1, 1]])\n",
    "\n",
    "# Equivalent to the previous integer array indexing example\n",
    "print(np.array([a[0, 1], a[0, 1]]))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "kaipSLafL9iU"
   },
   "source": [
    "One useful trick with integer array indexing is selecting or mutating one element from each row of a matrix:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 86
    },
    "colab_type": "code",
    "id": "ehqsV7TXL9iU",
    "outputId": "de509c40-4ee4-4b7c-e75d-1a936a3350e7"
   },
   "outputs": [],
   "source": [
    "# Create a new array from which we will select elements\n",
    "a = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12]])\n",
    "print(a)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 34
    },
    "colab_type": "code",
    "id": "pAPOoqy5L9iV",
    "outputId": "f812e29b-9218-4767-d3a8-e9854e754e68"
   },
   "outputs": [],
   "source": [
    "# Create an array of indices\n",
    "b = np.array([0, 2, 0, 1])\n",
    "\n",
    "# Select one element from each row of a using the indices in b\n",
    "print(a[np.arange(4), b])  # Prints \"[ 1  6  7 11]\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 86
    },
    "colab_type": "code",
    "id": "6v1PdI1DL9ib",
    "outputId": "89f50f82-de1b-4417-e55c-edbc0ee07584"
   },
   "outputs": [],
   "source": [
    "# Mutate one element from each row of a using the indices in b\n",
    "a[np.arange(4), b] += 10\n",
    "print(a)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "kaE8dBGgL9id"
   },
   "source": [
    "Boolean array indexing: Boolean array indexing lets you pick out arbitrary elements of an array. Frequently this type of indexing is used to select the elements of an array that satisfy some condition. Here is an example:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 69
    },
    "colab_type": "code",
    "id": "32PusjtKL9id",
    "outputId": "8782e8ec-b78d-44d7-8141-23e39750b854"
   },
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "a = np.array([[1,2], [3, 4], [5, 6]])\n",
    "\n",
    "bool_idx = (a > 2)  # Find the elements of a that are bigger than 2;\n",
    "                    # this returns a numpy array of Booleans of the same\n",
    "                    # shape as a, where each slot of bool_idx tells\n",
    "                    # whether that element of a is > 2.\n",
    "\n",
    "print(bool_idx)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 52
    },
    "colab_type": "code",
    "id": "cb2IRMXaL9if",
    "outputId": "5983f208-3738-472d-d6ab-11fe85b36c95"
   },
   "outputs": [],
   "source": [
    "# We use boolean array indexing to construct a rank 1 array\n",
    "# consisting of the elements of a corresponding to the True values\n",
    "# of bool_idx\n",
    "print(a[bool_idx])\n",
    "\n",
    "# We can do all of the above in a single concise statement:\n",
    "print(a[a > 2])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "CdofMonAL9ih"
   },
   "source": [
    "For brevity we have left out a lot of details about numpy array indexing; if you want to know more you should read the documentation."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "jTctwqdQL9ih"
   },
   "source": [
    "### Datatypes"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "kSZQ1WkIL9ih"
   },
   "source": [
    "Every numpy array is a grid of elements of the same type. Numpy provides a large set of numeric datatypes that you can use to construct arrays. Numpy tries to guess a datatype when you create an array, but functions that construct arrays usually also include an optional argument to explicitly specify the datatype. Here is an example:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 34
    },
    "colab_type": "code",
    "id": "4za4O0m5L9ih",
    "outputId": "2ea4fb80-a4df-43f9-c162-5665895c13ae"
   },
   "outputs": [],
   "source": [
    "x = np.array([1, 2])  # Let numpy choose the datatype\n",
    "y = np.array([1.0, 2.0])  # Let numpy choose the datatype\n",
    "z = np.array([1, 2], dtype=np.int64)  # Force a particular datatype\n",
    "\n",
    "print(x.dtype, y.dtype, z.dtype)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "RLVIsZQpL9ik"
   },
   "source": [
    "You can read all about numpy datatypes in the [documentation](http://docs.scipy.org/doc/numpy/reference/arrays.dtypes.html)."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "TuB-fdhIL9ik"
   },
   "source": [
    "### Array math"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "18e8V8elL9ik"
   },
   "source": [
    "Basic mathematical functions operate elementwise on arrays, and are available both as operator overloads and as functions in the numpy module:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 86
    },
    "colab_type": "code",
    "id": "gHKvBrSKL9il",
    "outputId": "a8a924b1-9d60-4b68-8fd3-e4657ae3f08b"
   },
   "outputs": [],
   "source": [
    "x = np.array([[1,2],[3,4]], dtype=np.float64)\n",
    "y = np.array([[5,6],[7,8]], dtype=np.float64)\n",
    "\n",
    "# Elementwise sum; both produce the array\n",
    "print(x + y)\n",
    "print(np.add(x, y))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 86
    },
    "colab_type": "code",
    "id": "1fZtIAMxL9in",
    "outputId": "122f1380-6144-4d6c-9d31-f62d839889a2"
   },
   "outputs": [],
   "source": [
    "# Elementwise difference; both produce the array\n",
    "print(x - y)\n",
    "print(np.subtract(x, y))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 86
    },
    "colab_type": "code",
    "id": "nil4AScML9io",
    "outputId": "038c8bb2-122b-4e59-c0a8-a091014fe68e"
   },
   "outputs": [],
   "source": [
    "# Elementwise product; both produce the array\n",
    "print(x * y)\n",
    "print(np.multiply(x, y))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 86
    },
    "colab_type": "code",
    "id": "0JoA4lH6L9ip",
    "outputId": "12351a74-7871-4bc2-97ce-a508bf4810da"
   },
   "outputs": [],
   "source": [
    "# Elementwise division; both produce the array\n",
    "# [[ 0.2         0.33333333]\n",
    "#  [ 0.42857143  0.5       ]]\n",
    "print(x / y)\n",
    "print(np.divide(x, y))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 52
    },
    "colab_type": "code",
    "id": "g0iZuA6bL9ir",
    "outputId": "29927dda-4167-4aa8-fbda-9008b09e4356"
   },
   "outputs": [],
   "source": [
    "# Elementwise square root; produces the array\n",
    "# [[ 1.          1.41421356]\n",
    "#  [ 1.73205081  2.        ]]\n",
    "print(np.sqrt(x))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "a5d_uujuL9it"
   },
   "source": [
    "Note that unlike MATLAB, `*` is elementwise multiplication, not matrix multiplication. We instead use the dot function to compute inner products of vectors, to multiply a vector by a matrix, and to multiply matrices. dot is available both as a function in the numpy module and as an instance method of array objects:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 52
    },
    "colab_type": "code",
    "id": "I3FnmoSeL9iu",
    "outputId": "46f4575a-2e5e-4347-a34e-0cc5bd280110"
   },
   "outputs": [],
   "source": [
    "x = np.array([[1,2],[3,4]])\n",
    "y = np.array([[5,6],[7,8]])\n",
    "\n",
    "v = np.array([9,10])\n",
    "w = np.array([11, 12])\n",
    "\n",
    "# Inner product of vectors; both produce 219\n",
    "print(v.dot(w))\n",
    "print(np.dot(v, w))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "vmxPbrHASVeA"
   },
   "source": [
    "You can also use the `@` operator which is equivalent to numpy's `dot` operator."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 34
    },
    "colab_type": "code",
    "id": "vyrWA-mXSdtt",
    "outputId": "a9aae545-2c93-4649-b220-b097655955f6"
   },
   "outputs": [],
   "source": [
    "print(v @ w)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 69
    },
    "colab_type": "code",
    "id": "zvUODeTxL9iw",
    "outputId": "4093fc76-094f-4453-a421-a212b5226968"
   },
   "outputs": [],
   "source": [
    "# Matrix / vector product; both produce the rank 1 array [29 67]\n",
    "print(x.dot(v))\n",
    "print(np.dot(x, v))\n",
    "print(x @ v)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 121
    },
    "colab_type": "code",
    "id": "3V_3NzNEL9iy",
    "outputId": "af2a89f9-af5d-47a6-9ad2-06a84b521b94"
   },
   "outputs": [],
   "source": [
    "# Matrix / matrix product; both produce the rank 2 array\n",
    "# [[19 22]\n",
    "#  [43 50]]\n",
    "print(x.dot(y))\n",
    "print(np.dot(x, y))\n",
    "print(x @ y)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "FbE-1If_L9i0"
   },
   "source": [
    "Numpy provides many useful functions for performing computations on arrays; one of the most useful is `sum`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 69
    },
    "colab_type": "code",
    "id": "DZUdZvPrL9i0",
    "outputId": "99cad470-d692-4b25-91c9-a57aa25f4c6e"
   },
   "outputs": [],
   "source": [
    "x = np.array([[1,2],[3,4]])\n",
    "\n",
    "print(np.sum(x))  # Compute sum of all elements; prints \"10\"\n",
    "print(np.sum(x, axis=0))  # Compute sum of each column; prints \"[4 6]\"\n",
    "print(np.sum(x, axis=1))  # Compute sum of each row; prints \"[3 7]\""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "ahdVW4iUL9i3"
   },
   "source": [
    "You can find the full list of mathematical functions provided by numpy in the [documentation](http://docs.scipy.org/doc/numpy/reference/routines.math.html).\n",
    "\n",
    "Apart from computing mathematical functions using arrays, we frequently need to reshape or otherwise manipulate data in arrays. The simplest example of this type of operation is transposing a matrix; to transpose a matrix, simply use the T attribute of an array object:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 104
    },
    "colab_type": "code",
    "id": "63Yl1f3oL9i3",
    "outputId": "c75ac7ba-4351-42f8-a09c-a4e0d966ab50"
   },
   "outputs": [],
   "source": [
    "print(x)\n",
    "print(\"transpose\\n\", x.T)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 104
    },
    "colab_type": "code",
    "id": "mkk03eNIL9i4",
    "outputId": "499eec5a-55b7-473a-d4aa-9d023d63885a"
   },
   "outputs": [],
   "source": [
    "v = np.array([[1,2,3]])\n",
    "print(v )\n",
    "print(\"transpose\\n\", v.T)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "REfLrUTcL9i7"
   },
   "source": [
    "### Broadcasting"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "EygGAMWqL9i7"
   },
   "source": [
    "Broadcasting is a powerful mechanism that allows numpy to work with arrays of different shapes when performing arithmetic operations. Frequently we have a smaller array and a larger array, and we want to use the smaller array multiple times to perform some operation on the larger array.\n",
    "\n",
    "For example, suppose that we want to add a constant vector to each row of a matrix. We could do it like this:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 86
    },
    "colab_type": "code",
    "id": "WEEvkV1ZL9i7",
    "outputId": "3896d03c-3ece-4aa8-f675-aef3a220574d"
   },
   "outputs": [],
   "source": [
    "# We will add the vector v to each row of the matrix x,\n",
    "# storing the result in the matrix y\n",
    "x = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12]])\n",
    "v = np.array([1, 0, 1])\n",
    "y = np.empty_like(x)   # Create an empty matrix with the same shape as x\n",
    "\n",
    "# Add the vector v to each row of the matrix x with an explicit loop\n",
    "for i in range(4):\n",
    "    y[i, :] = x[i, :] + v\n",
    "\n",
    "print(y)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "2OlXXupEL9i-"
   },
   "source": [
    "This works; however when the matrix `x` is very large, computing an explicit loop in Python could be slow. Note that adding the vector v to each row of the matrix `x` is equivalent to forming a matrix `vv` by stacking multiple copies of `v` vertically, then performing elementwise summation of `x` and `vv`. We could implement this approach like this:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 86
    },
    "colab_type": "code",
    "id": "vS7UwAQQL9i-",
    "outputId": "8621e502-c25d-4a18-c973-886dbfd1df36"
   },
   "outputs": [],
   "source": [
    "vv = np.tile(v, (4, 1))  # Stack 4 copies of v on top of each other\n",
    "print(vv)                # Prints \"[[1 0 1]\n",
    "                         #          [1 0 1]\n",
    "                         #          [1 0 1]\n",
    "                         #          [1 0 1]]\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 86
    },
    "colab_type": "code",
    "id": "N0hJphSIL9jA",
    "outputId": "def6a757-170c-43bf-8728-732dfb133273"
   },
   "outputs": [],
   "source": [
    "y = x + vv  # Add x and vv elementwise\n",
    "print(y)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "zHos6RJnL9jB"
   },
   "source": [
    "Numpy broadcasting allows us to perform this computation without actually creating multiple copies of v. Consider this version, using broadcasting:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 86
    },
    "colab_type": "code",
    "id": "vnYFb-gYL9jC",
    "outputId": "df3bea8a-ad72-4a83-90bb-306b55c6fb93"
   },
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "# We will add the vector v to each row of the matrix x,\n",
    "# storing the result in the matrix y\n",
    "x = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12]])\n",
    "v = np.array([1, 0, 1])\n",
    "y = x + v  # Add v to each row of x using broadcasting\n",
    "print(y)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "08YyIURKL9jH"
   },
   "source": [
    "The line `y = x + v` works even though `x` has shape `(4, 3)` and `v` has shape `(3,)` due to broadcasting; this line works as if v actually had shape `(4, 3)`, where each row was a copy of `v`, and the sum was performed elementwise.\n",
    "\n",
    "Broadcasting two arrays together follows these rules:\n",
    "\n",
    "1. If the arrays do not have the same rank, prepend the shape of the lower rank array with 1s until both shapes have the same length.\n",
    "2. The two arrays are said to be compatible in a dimension if they have the same size in the dimension, or if one of the arrays has size 1 in that dimension.\n",
    "3. The arrays can be broadcast together if they are compatible in all dimensions.\n",
    "4. After broadcasting, each array behaves as if it had shape equal to the elementwise maximum of shapes of the two input arrays.\n",
    "5. In any dimension where one array had size 1 and the other array had size greater than 1, the first array behaves as if it were copied along that dimension\n",
    "\n",
    "If this explanation does not make sense, try reading the explanation from the [documentation](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) or this [explanation](http://wiki.scipy.org/EricsBroadcastingDoc).\n",
    "\n",
    "Functions that support broadcasting are known as universal functions. You can find the list of all universal functions in the [documentation](http://docs.scipy.org/doc/numpy/reference/ufuncs.html#available-ufuncs).\n",
    "\n",
    "Here are some applications of broadcasting:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 69
    },
    "colab_type": "code",
    "id": "EmQnwoM9L9jH",
    "outputId": "f59e181e-e2d4-416c-d094-c4d003ce8509"
   },
   "outputs": [],
   "source": [
    "# Compute outer product of vectors\n",
    "v = np.array([1,2,3])  # v has shape (3,)\n",
    "w = np.array([4,5])    # w has shape (2,)\n",
    "# To compute an outer product, we first reshape v to be a column\n",
    "# vector of shape (3, 1); we can then broadcast it against w to yield\n",
    "# an output of shape (3, 2), which is the outer product of v and w:\n",
    "\n",
    "print(np.reshape(v, (3, 1)) * w)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 52
    },
    "colab_type": "code",
    "id": "PgotmpcnL9jK",
    "outputId": "567763d3-073a-4e3c-9ebe-6c7d2b6d3446"
   },
   "outputs": [],
   "source": [
    "# Add a vector to each row of a matrix\n",
    "x = np.array([[1,2,3], [4,5,6]])\n",
    "# x has shape (2, 3) and v has shape (3,) so they broadcast to (2, 3),\n",
    "# giving the following matrix:\n",
    "\n",
    "print(x + v)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 52
    },
    "colab_type": "code",
    "id": "T5hKS1QaL9jK",
    "outputId": "5f14ac5c-7a21-4216-e91d-cfce5720a804"
   },
   "outputs": [],
   "source": [
    "# Add a vector to each column of a matrix\n",
    "# x has shape (2, 3) and w has shape (2,).\n",
    "# If we transpose x then it has shape (3, 2) and can be broadcast\n",
    "# against w to yield a result of shape (3, 2); transposing this result\n",
    "# yields the final result of shape (2, 3) which is the matrix x with\n",
    "# the vector w added to each column. Gives the following matrix:\n",
    "\n",
    "print((x.T + w).T)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 52
    },
    "colab_type": "code",
    "id": "JDUrZUl6L9jN",
    "outputId": "53e99a89-c599-406d-9fe3-7aa35ae5fb90"
   },
   "outputs": [],
   "source": [
    "# Another solution is to reshape w to be a row vector of shape (2, 1);\n",
    "# we can then broadcast it directly against x to produce the same\n",
    "# output.\n",
    "print(x + np.reshape(w, (2, 1)))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 52
    },
    "colab_type": "code",
    "id": "VzrEo4KGL9jP",
    "outputId": "53c9d4cc-32d5-46b0-d090-53c7db57fb32"
   },
   "outputs": [],
   "source": [
    "# Multiply a matrix by a constant:\n",
    "# x has shape (2, 3). Numpy treats scalars as arrays of shape ();\n",
    "# these can be broadcast together to shape (2, 3), producing the\n",
    "# following array:\n",
    "print(x * 2)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "89e2FXxFL9jQ"
   },
   "source": [
    "Broadcasting typically makes your code more concise and faster, so you should strive to use it where possible."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "iF3ZtwVNL9jQ"
   },
   "source": [
    "This brief overview has touched on many of the important things that you need to know about numpy, but is far from complete. Check out the [numpy reference](http://docs.scipy.org/doc/numpy/reference/) to find out much more about numpy."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "tEINf4bEL9jR"
   },
   "source": [
    "## Matplotlib"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "0hgVWLaXL9jR"
   },
   "source": [
    "Matplotlib is a plotting library. In this section give a brief introduction to the `matplotlib.pyplot` module, which provides a plotting system similar to that of MATLAB."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "cmh_7c6KL9jR"
   },
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "jOsaA5hGL9jS"
   },
   "source": [
    "By running this special iPython command, we will be displaying plots inline:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "ijpsmwGnL9jT"
   },
   "outputs": [],
   "source": [
    "%matplotlib inline"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "U5Z_oMoLL9jV"
   },
   "source": [
    "### Plotting"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "6QyFJ7dhL9jV"
   },
   "source": [
    "The most important function in `matplotlib` is plot, which allows you to plot 2D data. Here is a simple example:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 282
    },
    "colab_type": "code",
    "id": "pua52BGeL9jW",
    "outputId": "9ac3ee0f-7ff7-463b-b901-c33d21a2b10c"
   },
   "outputs": [],
   "source": [
    "# Compute the x and y coordinates for points on a sine curve\n",
    "x = np.arange(0, 3 * np.pi, 0.1)\n",
    "y = np.sin(x)\n",
    "\n",
    "# Plot the points using matplotlib\n",
    "plt.plot(x, y)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "9W2VAcLiL9jX"
   },
   "source": [
    "With just a little bit of extra work we can easily plot multiple lines at once, and add a title, legend, and axis labels:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 312
    },
    "colab_type": "code",
    "id": "TfCQHJ5AL9jY",
    "outputId": "fdb9c033-0f06-4041-a69d-a0f3a54c7206"
   },
   "outputs": [],
   "source": [
    "y_sin = np.sin(x)\n",
    "y_cos = np.cos(x)\n",
    "\n",
    "# Plot the points using matplotlib\n",
    "plt.plot(x, y_sin)\n",
    "plt.plot(x, y_cos)\n",
    "plt.xlabel('x axis label')\n",
    "plt.ylabel('y axis label')\n",
    "plt.title('Sine and Cosine')\n",
    "plt.legend(['Sine', 'Cosine'])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "R5IeAY03L9ja"
   },
   "source": [
    "### Subplots "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "CfUzwJg0L9ja"
   },
   "source": [
    "You can plot different things in the same figure using the subplot function. Here is an example:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 281
    },
    "colab_type": "code",
    "id": "dM23yGH9L9ja",
    "outputId": "14dfa5ea-f453-4da5-a2ee-fea0de8f72d9"
   },
   "outputs": [],
   "source": [
    "# Compute the x and y coordinates for points on sine and cosine curves\n",
    "x = np.arange(0, 3 * np.pi, 0.1)\n",
    "y_sin = np.sin(x)\n",
    "y_cos = np.cos(x)\n",
    "\n",
    "# Set up a subplot grid that has height 2 and width 1,\n",
    "# and set the first such subplot as active.\n",
    "plt.subplot(2, 1, 1)\n",
    "\n",
    "# Make the first plot\n",
    "plt.plot(x, y_sin)\n",
    "plt.title('Sine')\n",
    "\n",
    "# Set the second subplot as active, and make the second plot.\n",
    "plt.subplot(2, 1, 2)\n",
    "plt.plot(x, y_cos)\n",
    "plt.title('Cosine')\n",
    "\n",
    "# Show the figure.\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "gLtsST5SL9jc"
   },
   "source": [
    "You can read much more about the `subplot` function in the [documentation](http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.subplot)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "colab": {
   "collapsed_sections": [],
   "name": "colab-tutorial.ipynb",
   "provenance": []
  },
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.13.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
