{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Mostly inspired from the tutorial of Justin Johnson in class [CS231](http://cs231n.github.io/python-numpy-tutorial/). Completed and modified by Jean Hennebert in 2020.\n",
    "\n",
    "# Numpy quick tutorial\n",
    "\n",
    "\n",
    "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 useful to get started with Numpy.\n",
    "\n",
    "## Numpy arrays\n",
    "A numpy array is a grid of values, all of the same type, and is indexed by integers. The number of *dimensions* is called the *rank* of the array. The *shape* of an array is a tuple of integers giving the size of the array along each dimension. For example, a $3 \\times 3$ 2D matrix has a rank 2 and shape `(3,3)`.\n",
    "\n",
    "We can initialize numpy arrays from Python lists, and access elements using square brackets. An array initialized fom a simple Python list is equivalent to a mathematical vector."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'numpy.ndarray'>\n",
      "[1 2 3]\n",
      "(3,)\n",
      "1\n",
      "1 2 3\n",
      "[5 2 3]\n"
     ]
    }
   ],
   "source": [
    "import numpy as np\n",
    "\n",
    "a = np.array([1, 2, 3])   # Create a rank 1 array from a list\n",
    "print(type(a))            # Prints \"<class 'numpy.ndarray'>\"\n",
    "print(a)                  # Prints \"[1,2,3]\"\n",
    "print(a.shape)            # Prints \"(3,)\", i.e. we have an array of 1 dimension (rank 1) with 3 elements\n",
    "print(a[0])               # a[0] is the value at index 0 in the array, prints \"0\"\n",
    "print(a[0], a[1], a[2])   # Prints \"1 2 3\"\n",
    "a[0] = 5                  # Changes an element of the array, here the element at index 0 takes now 5 as value\n",
    "print(a)                  # Prints the array as \"[5, 2, 3]\""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Arrays are not mutable in size once created. Check this out."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "a = np.array([1, 2, 3])   # Create a rank 1 array from a list\n",
    "# a[3] = 4                  # This attempt to set a value in 3rd position triggers an error, size can't change"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "As arrays are containing values of the same type, upward automatic conversions occurs such as from int to float, or from numeric values to strings. The result is an array with homogeneous types."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1. 2. 3. 4.]\n",
      "['1' '2' '3.0' 'hi']\n"
     ]
    }
   ],
   "source": [
    "b = np.array([1, 2, 3, 4.0])  # As arrays do not allow type mixing, automatic conversions occurs\n",
    "print(b)                      # In b, ints are converted to float because of the presence of the float 4.0\n",
    "c = np.array([1, 2, 3.0, 'hi']) \n",
    "print(c)                      # In c, all numeric values are converted to strings"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Arrays can be defined with 2 dimensions by using nested lists. Typically, rank 2 arrays are used to represent matrices."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[1 2 3]\n",
      " [4 5 6]]\n",
      "(2, 3)\n",
      "[1 2 3]\n",
      "3\n",
      "3\n",
      "1 2 4\n"
     ]
    }
   ],
   "source": [
    "b = np.array([[1,2,3],[4,5,6]]) # Create a rank 2 array, equivalent to a 2X3 matrix\n",
    "print(b)\n",
    "print(b.shape)                  # Prints \"(2, 3)\", i.e. we have an array of 2 dims with 2 lines and 3 columns\n",
    "print(b[0])                     # Prints the 1st element along dim 1, which is an array of rank 1, first line of matrix\n",
    "print(b[0,2])                   # b[0,0] is the elements in position 0 along dim 1 and 2 along dim 2\n",
    "print(b[0][2])                  # equivalent to b[0,2]\n",
    "print(b[0,0], b[0,1], b[1,0])   # Prints \"1 2 4\""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Array creation\n",
    "Numpy also provides many functions to create arrays:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[0 1 2 3]\n",
      "[10 15 20 25 30 35 40 45 50 55 60 65 70 75 80 85 90 95]\n",
      "[ 0.  3.  6.  9. 12. 15. 18. 21.]\n",
      "[[0. 0.]\n",
      " [0. 0.]]\n",
      "[[1. 1.]]\n",
      "[[7 7]\n",
      " [7 7]]\n",
      "[[1. 0.]\n",
      " [0. 1.]]\n",
      "[[0.31175397 0.01513045]\n",
      " [0.21705725 0.48677915]]\n"
     ]
    }
   ],
   "source": [
    "v = np.arange(4)      # Create a 1 dim array of increasing values from 0 to 3\n",
    "print(v)              # Print \"[0 1 2 3]\n",
    "\n",
    "w = np.arange(10,100,5) # Create a 1 dim array of int values between 10 and 100 (excluded), by step of 5\n",
    "print(w)              # Print [10 15 20 25 30 35 40 45 50 55 60 65 70 75 80 85 90 95]\n",
    "\n",
    "x = np.linspace(0,21,8) # Create a 1 dim array of 8 float values linearly spaced between 0 and 21\n",
    "print(x)              # Print [ 0.  3.  6.  9. 12. 15. 18. 21.]\n",
    "\n",
    "a = np.zeros((2,2))   # Create an array full of zeros\n",
    "print(a)              # Print  \"[[ 0.  0.]\n",
    "                      #          [ 0.  0.]]\"\n",
    "                      # The tuple (2,2) specifies the shape of the array\n",
    "\n",
    "b = np.ones((1,2))    # Create an array of ones\n",
    "print(b)              # Print  \"[[ 1.  1.]]\"\n",
    "\n",
    "c = np.full((2,2), 7)  # Create an array full of the given value, 7 here\n",
    "print(c)               # Print  \"[[ 7.  7.]\n",
    "                       #          [ 7.  7.]]\"\n",
    "\n",
    "d = np.eye(2)         # Create a 2x2 identity matrix\n",
    "print(d)              # Print  \"[[ 1.  0.]\n",
    "                      #          [ 0.  1.]]\"\n",
    "\n",
    "e = np.random.random((2,2))  # Create an array filled with random values\n",
    "print(e)                     # Might print \"[[ 0.91940167  0.08143941]\n",
    "                             #               [ 0.68744134  0.87236687]]\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Array indexing\n",
    "Numpy offers several ways to index into arrays and we provide here a selection of useful tricks that may be useful for array manipulation in the context of Machine Learning exercises. The full indexing documentation can be found [here](https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html).\n",
    "\n",
    "Accessing single elements has been shown above.\n",
    "\n",
    "**Slicing**. In a similar way as for Python lists, numpy arrays can be sliced. Since arrays may be multidimensional, you must specify a slice for each dimension of the array.\n",
    "\n",
    "**Vues**. A slice produces a reference to a vue of the same data, meaning that if you change a value in the output of a slice, it will modify the original array.\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2\n",
      "77\n"
     ]
    }
   ],
   "source": [
    "# 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]   # :2 means all values up to index 2 (excluded), 1:3 means all values from 1 to 3 (excluded)\n",
    "\n",
    "# A slice of an array is a view into the same data, so modifying it\n",
    "# will modify the original array.\n",
    "print(a[0, 1])   # Prints \"2\"\n",
    "b[0, 0] = 77     # b[0, 0] is the same piece of data as a[0, 1]\n",
    "print(a[0, 1])   # Prints \"77\""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You can also mix integer indexing with slice indexing. However, doing so will yield an array of lower rank than the original array."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[5 6 7 8] (4,)\n",
      "[[5 6 7 8]] (1, 4)\n",
      "[ 2  6 10] (3,)\n",
      "[[ 2]\n",
      " [ 6]\n",
      " [10]] (3, 1)\n"
     ]
    }
   ],
   "source": [
    "# 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",
    "# 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:\n",
    "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",
    "print(row_r1, row_r1.shape)  # Prints \"[5 6 7 8] (4,)\"\n",
    "print(row_r2, row_r2.shape)  # Prints \"[[5 6 7 8]] (1, 4)\"\n",
    "\n",
    "# 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)  # Prints \"[ 2  6 10] (3,)\"\n",
    "print(col_r2, col_r2.shape)  # Prints \"[[ 2]\n",
    "                             #          [ 6]\n",
    "                             #          [10]] (3, 1)\""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "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, doing copies of the original values. Here are some examples:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1 4 5]\n",
      "[1 4 5]\n",
      "[2 2]\n",
      "[2 2]\n"
     ]
    }
   ],
   "source": [
    "# Create the following rank 2 array with shape (3, 2)\n",
    "# [[ 1  2 ]\n",
    "#  [ 3  4 ]\n",
    "#  [ 5  6 ]]\n",
    "a = np.array([[1, 2], [3, 4], [5, 6]])\n",
    "\n",
    "# Here is an example of integer array indexing. The returned array will have shape (3,)\n",
    "print(a[[0, 1, 2], [0, 1, 0]])  # Prints \"[1 4 5]\"\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]]))  # Prints \"[1 4 5]\"\n",
    "\n",
    "# When using integer array indexing, you can reuse the same\n",
    "# element from the source array:\n",
    "print(a[[0, 0], [1, 1]])  # Prints \"[2 2]\"\n",
    "\n",
    "# Equivalent to the previous integer array indexing example\n",
    "print(np.array([a[0, 1], a[0, 1]]))  # Prints \"[2 2]\""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "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": 11,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[ 1  2  3]\n",
      " [ 4  5  6]\n",
      " [ 7  8  9]\n",
      " [10 11 12]]\n",
      "[ 1  6  7 11]\n",
      "[[11  2  3]\n",
      " [ 4  5 16]\n",
      " [17  8  9]\n",
      " [10 21 12]]\n"
     ]
    }
   ],
   "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",
    "\n",
    "print(a)  # prints \"[[ 1,  2,  3],\n",
    "          #          [ 4,  5,  6],\n",
    "          #          [ 7,  8,  9],\n",
    "          #          [10, 11, 12]]\"\n",
    "\n",
    "# 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]\"\n",
    "\n",
    "# Mutate one element from each row of a using the indices in b\n",
    "a[np.arange(4), b] += 10\n",
    "\n",
    "print(a)  # prints \"array([[11,  2,  3],\n",
    "          #                [ 4,  5, 16],\n",
    "          #                [17,  8,  9],\n",
    "          #                [10, 21, 12]])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "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": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[False False]\n",
      " [ True  True]\n",
      " [ True  True]]\n",
      "[3 4 5 6]\n",
      "[3 4 5 6]\n"
     ]
    }
   ],
   "source": [
    "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)      # Prints \"[[False False]\n",
    "                     #          [ True  True]\n",
    "                     #          [ True  True]]\"\n",
    "\n",
    "# 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])  # Prints \"[3 4 5 6]\"\n",
    "\n",
    "# We can do all of the above in a single concise statement:\n",
    "print(a[a > 2])     # Prints \"[3 4 5 6]\""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Datatypes\n",
    "\n",
    "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 (see the [doc](https://docs.scipy.org/doc/numpy/reference/arrays.dtypes.html)). 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": 13,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "int64\n",
      "float64\n",
      "int64\n"
     ]
    }
   ],
   "source": [
    "x = np.array([1, 2])   # Let numpy choose the datatype\n",
    "print(x.dtype)         # Prints \"int64\"\n",
    "\n",
    "x = np.array([1.0, 2.0])   # Let numpy choose the datatype\n",
    "print(x.dtype)             # Prints \"float64\"\n",
    "\n",
    "x = np.array([1, 2], dtype=np.int64)   # Force a particular datatype\n",
    "print(x.dtype)                         # Prints \"int64\""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Array math\n",
    "\n",
    "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": 14,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[ 6.  8.]\n",
      " [10. 12.]]\n",
      "[[ 6.  8.]\n",
      " [10. 12.]]\n",
      "[[-4. -4.]\n",
      " [-4. -4.]]\n",
      "[[-4. -4.]\n",
      " [-4. -4.]]\n",
      "[[ 5. 12.]\n",
      " [21. 32.]]\n",
      "[[ 5. 12.]\n",
      " [21. 32.]]\n",
      "[[0.2        0.33333333]\n",
      " [0.42857143 0.5       ]]\n",
      "[[0.2        0.33333333]\n",
      " [0.42857143 0.5       ]]\n",
      "[[1.         1.41421356]\n",
      " [1.73205081 2.        ]]\n"
     ]
    }
   ],
   "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",
    "# [[ 6.0  8.0]\n",
    "#  [10.0 12.0]]\n",
    "print(x + y)\n",
    "print(np.add(x, y))\n",
    "\n",
    "# Elementwise difference; both produce the array\n",
    "# [[-4.0 -4.0]\n",
    "#  [-4.0 -4.0]]\n",
    "print(x - y)\n",
    "print(np.subtract(x, y))\n",
    "\n",
    "# Elementwise product; both produce the array\n",
    "# [[ 5.0 12.0]\n",
    "#  [21.0 32.0]]\n",
    "print(x * y)\n",
    "print(np.multiply(x, y))\n",
    "\n",
    "# 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))\n",
    "\n",
    "# Elementwise square root; produces the array\n",
    "# [[ 1.          1.41421356]\n",
    "#  [ 1.73205081  2.        ]]\n",
    "print(np.sqrt(x))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "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": 15,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "23\n",
      "23\n",
      "[ 8 18]\n",
      "[ 8 18]\n",
      "[[19 22]\n",
      " [43 50]]\n",
      "[[19 22]\n",
      " [43 50]]\n"
     ]
    }
   ],
   "source": [
    "x = np.array([[1,2],[3,4]])\n",
    "y = np.array([[5,6],[7,8]])\n",
    "\n",
    "v = np.array([2, 3])\n",
    "w = np.array([4, 5])\n",
    "\n",
    "# Inner product of vectors; both produce 23\n",
    "print(v.dot(w))\n",
    "print(np.dot(v, w))\n",
    "\n",
    "# Matrix / vector product; both produce the rank 1 array [8 18]\n",
    "print(x.dot(v))\n",
    "print(np.dot(x, v))\n",
    "\n",
    "# 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))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Numpy provides many useful functions for performing computations on arrays; one of the most useful is `sum`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "10\n",
      "[4 6]\n",
      "[3 7]\n"
     ]
    }
   ],
   "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": {},
   "source": [
    "You can find the full list of mathematical functions provided by numpy in the [documentation](https://docs.scipy.org/doc/numpy/reference/routines.math.html).\n",
    "\n",
    "## Array manipulation\n",
    "Apart from computing mathematical functions using arrays, we frequently need to reshape or otherwise manipulate data in arrays. The [documentation](https://docs.scipy.org/doc/numpy/reference/routines.array-manipulation.html) is exhaustive about array manipulation. 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": 17,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[1 2]\n",
      " [3 4]]\n",
      "[[1 3]\n",
      " [2 4]]\n",
      "[1 2 3]\n",
      "[1 2 3]\n"
     ]
    }
   ],
   "source": [
    "x = np.array([[1,2], [3,4]])\n",
    "print(x)    # Prints \"[[1 2]\n",
    "            #          [3 4]]\"\n",
    "print(x.T)  # Prints \"[[1 3]\n",
    "            #          [2 4]]\"\n",
    "\n",
    "# Note that taking the transpose of a rank 1 array does nothing:\n",
    "v = np.array([1,2,3])\n",
    "print(v)    # Prints \"[1 2 3]\"\n",
    "print(v.T)  # Prints \"[1 2 3]\""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Broadcasting\n",
    "\n",
    "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": 18,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[ 2  2  4]\n",
      " [ 5  5  7]\n",
      " [ 8  8 10]\n",
      " [11 11 13]]\n"
     ]
    }
   ],
   "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",
    "# Now y is the following\n",
    "# [[ 2  2  4]\n",
    "#  [ 5  5  7]\n",
    "#  [ 8  8 10]\n",
    "#  [11 11 13]]\n",
    "print(y)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "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": 19,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[1 0 1]\n",
      " [1 0 1]\n",
      " [1 0 1]\n",
      " [1 0 1]]\n",
      "[[ 2  2  4]\n",
      " [ 5  5  7]\n",
      " [ 8  8 10]\n",
      " [11 11 13]]\n"
     ]
    }
   ],
   "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",
    "vv = np.tile(v, (4,1))   # Stack 4 copies of v on top of each other.\n",
    "                         # (4,1) means 4 times on the \"line\" dimension and 1 time on the \"row\" dimension\n",
    "print(vv)                # Prints \"[[1 0 1]\n",
    "                         #          [1 0 1]\n",
    "                         #          [1 0 1]\n",
    "                         #          [1 0 1]]\"\n",
    "y = x + vv  # Add x and vv elementwise\n",
    "print(y)  # Prints \"[[ 2  2  4\n",
    "          #          [ 5  5  7]\n",
    "          #          [ 8  8 10]\n",
    "          #          [11 11 13]]\""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "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": 20,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[ 2  2  4]\n",
      " [ 5  5  7]\n",
      " [ 8  8 10]\n",
      " [11 11 13]]\n"
     ]
    }
   ],
   "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 = x + v  # Add v to each row of x using broadcasting\n",
    "print(y)  # Prints \"[[ 2  2  4]\n",
    "          #          [ 5  5  7]\n",
    "          #          [ 8  8 10]\n",
    "          #          [11 11 13]]\""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "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](https://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) or this [explanation](https://scipy.github.io/old-wiki/pages/EricsBroadcastingDoc).\n",
    "\n",
    "Functions that support broadcasting are known as universal functions. You can find the list of all universal functions in the [documentation](https://docs.scipy.org/doc/numpy/reference/ufuncs.html#available-ufuncs).\n",
    "\n",
    "Here are some applications of broadcasting:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[ 4  5]\n",
      " [ 8 10]\n",
      " [12 15]]\n",
      "[[2 4 6]\n",
      " [5 7 9]]\n",
      "[[ 5  6  7]\n",
      " [ 9 10 11]]\n",
      "[[ 5  6  7]\n",
      " [ 9 10 11]]\n",
      "[[ 2  4  6]\n",
      " [ 8 10 12]]\n"
     ]
    }
   ],
   "source": [
    "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",
    "# [[ 4  5]\n",
    "#  [ 8 10]\n",
    "#  [12 15]]\n",
    "print(np.reshape(v, (3, 1)) * w)\n",
    "\n",
    "# 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",
    "# [[2 4 6]\n",
    "#  [5 7 9]]\n",
    "print(x + v)\n",
    "\n",
    "# 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",
    "# [[ 5  6  7]\n",
    "#  [ 9 10 11]]\n",
    "print((x.T + w).T)\n",
    "# Another solution is to reshape w to be a column 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)))\n",
    "\n",
    "# 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",
    "# [[ 2  4  6]\n",
    "#  [ 8 10 12]]\n",
    "print(x * 2)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Images\n",
    "\n",
    "You can use the imshow function to show images. Here is an example:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(480, 320, 3)\n"
     ]
    },
    {
     "data": {
      "image/png": "[encoded data, 1021244 characters]",
      "text/plain": [
       "<Figure size 1000x1000 with 2 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "import imageio.v3 as iio\n",
    "import matplotlib.pyplot as plt\n",
    "import numpy as np\n",
    "\n",
    "img = iio.imread('sponge-bob.jpg')\n",
    "print(img.shape)\n",
    "img_tinted = img * [0.8, 0.8, 0.8]\n",
    "\n",
    "plt.figure(figsize=(10, 10))\n",
    "\n",
    "# Show the original image\n",
    "plt.subplot(1, 2, 1)\n",
    "plt.imshow(img)\n",
    "\n",
    "# Show the tinted image\n",
    "plt.subplot(1, 2, 2)\n",
    "# A slight gotcha with imshow is that it might give strange results\n",
    "# if presented with data that is not uint8. To work around this, we\n",
    "# explicitly cast the image to uint8 before displaying it.\n",
    "plt.imshow(np.uint8(img_tinted))\n",
    "\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 823276 characters]",
      "text/plain": [
       "<Figure size 1500x500 with 3 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "#######################################################################\n",
    "# TODO:                                                               #\n",
    "# Show the red, green and blue components of the image in 3 different #\n",
    "# sub-plots                                                           #\n",
    "#######################################################################\n",
    "\n",
    "plt.figure(figsize=(15, 5))\n",
    "\n",
    "# RGB format : img[red, green, blue] -> img[:,:,0], img[:,:,1], img[:,:,2]\n",
    "\n",
    "# Red channel\n",
    "plt.subplot(1, 3, 1)\n",
    "plt.imshow(img[:,:,0], cmap='Reds')\n",
    "plt.title('Red Channel')\n",
    "\n",
    "# Green channel\n",
    "plt.subplot(1, 3, 2)\n",
    "plt.imshow(img[:,:,1], cmap='Greens')\n",
    "plt.title('Green Channel')\n",
    "\n",
    "# Blue channel\n",
    "plt.subplot(1, 3, 3)\n",
    "plt.imshow(img[:,:,2], cmap='Blues')\n",
    "plt.title('Blue Channel')\n",
    "\n",
    "plt.show()\n",
    "\n",
    "\n",
    "#######################################################################\n",
    "#                         END OF YOUR CODE                            #\n",
    "#######################################################################"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 877332 characters]",
      "text/plain": [
       "<Figure size 1500x500 with 3 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "#######################################################################\n",
    "# TODO:                                                               #\n",
    "# Perform the following distorsion of the image and display it        #\n",
    "#  - vertical flip                                                    #\n",
    "#  - rotation 90 degrees                                              #\n",
    "#  - horizontal flip\n",
    "# Hint: have a look at the np.fliplr() function                       #\n",
    "#######################################################################\n",
    "\n",
    "plt.figure(figsize=(15, 5))\n",
    "\n",
    "# Vertical flip\n",
    "plt.subplot(1, 3, 1)\n",
    "plt.imshow(np.flipud(img))\n",
    "plt.title('Vertical Flip')\n",
    "\n",
    "# Rotation 90 degrees\n",
    "plt.subplot(1, 3, 2)\n",
    "plt.imshow(np.rot90(img))\n",
    "plt.title('Rotation 90 Degrees')\n",
    "\n",
    "# Horizontal flip\n",
    "plt.subplot(1, 3, 3)\n",
    "plt.imshow(np.fliplr(img))\n",
    "plt.title('Horizontal Flip')\n",
    "\n",
    "plt.show()\n",
    "\n",
    "\n",
    "#######################################################################\n",
    "#                         END OF YOUR CODE                            #\n",
    "#######################################################################"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "MLvenv",
   "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.10.18"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
