{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "\n", "\n", "\"Open\n", "\n", "| - | - | - |\n", "|-----------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------|\n", "| [Exercise 11 (rows and columns)](<#Exercise-11-(rows-and-columns)>) | [Exercise 12 (row and column vectors)](<#Exercise-12-(row-and-column-vectors)>) | [Exercise 13 (diamond)](<#Exercise-13-(diamond)>) |\n", "| [Exercise 14 (vector lengths)](<#Exercise-14-(vector-lengths)>) | [Exercise 15 (vector angles)](<#Exercise-15-(vector-angles)>) | [Exercise 16 (multiplication table revisited)](<#Exercise-16-(multiplication-table-revisited)>) |\n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# NumPy\n", "\n", "[NumPy](https://docs.scipy.org/doc/numpy/) is a Python library for handling multi-dimensional arrays. It contains both the data structures needed for the storing and accessing arrays, and operations and functions for computation using these arrays. Although the arrays are usually used for storing numbers, other type of data can be stored as well, such as strings. Unlike lists in core Python, NumPy's fundamental data structure, the array, must have the same data type for all its elements. The homogeneity of arrays allows highly optimized functions that use arrays as their inputs and outputs.\n", "\n", "There are several uses for high-dimensional arrays in data analysis. For instance, they can be used to:\n", "\n", "* store matrices, solve systems of linear equations, find eigenvalues/vectors, find matrix decompositions, and solve other problems familiar from linear algebra\n", "* store multi-dimensional measurement data. For example, an element `a[i,j]` in a 2-dimensional array might store the temperature $t_{ij}$ measured at coordinates i, j on a 2-dimension surface.\n", "* images and videos can be represented as NumPy arrays:\n", "\n", " * a gray-scale image can be represented as a two dimensional array\n", " * a color image can be represented as a three dimensional image, the third dimension contains the color components red, green, and blue\n", " * a color video can be represented as a four dimensional array\n", "* a 2-dimensional table might store a sequence of *samples*, and each sample might be divided into *features*. For example, we could measure the weather conditions once per day, and the conditions could include the temperature, direction and speed of wind, and the amount of rain. Then we would have one sample per day, and the features would be the temperature, wind, and rain. In the standard representation of this kind of tabular data, the rows corresponds to samples and the columns correspond to features. We see more of this kind of data in the chapters on Pandas and Scikit-learn.\n", "\n", "In this chapter we will go through:\n", "\n", "* Creation of arrays\n", "* Array types and attributes\n", "* Accessing arrays with indexing and slicing\n", "* Reshaping of arrays\n", "* Combining and splitting arrays\n", "* Fast operations on arrays\n", "* Aggregations of arrays\n", "* Rules of binary array operations\n", "* Matrix operations familiar from linear algebra" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We start by importing the NumPy library, and we use the standard abbreviation `np` for it." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import numpy as np" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Creation of arrays\n", "There are several ways of creating NumPy arrays. One way is to give a (nested) list as a parameter to the `array` constructor:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "np.array([1,2,3]) # one dimensional array" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Note that leaving out the brackets from the above expression, i.e. calling `np.array(1,2,3)` will result in an error." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Two dimensional array can be given by listing the rows of the array:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "np.array([[1,2,3], [4,5,6]])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Similarly, three dimensional array can be described as a list of lists of lists:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "np.array([[[1,2], [3,4]], [[5,6], [7,8]]])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "There are some helper functions to create common types of arrays:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "np.zeros((3,4))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "To specify that elements are `int`s instead of `float`s, use the parameter `dtype`:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "np.zeros((3,4), dtype=int)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Similarly `ones` initializes all elements to one, `full` initializes all elements to a specified value, and `empty` leaves the elements uninitialized:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "np.ones((2,3))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "np.full((2,3), fill_value=7)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "np.empty((2,4))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The `eye` function creates the identity matrix, that is, a matrix with elements on the diagonal are set to one, and non-diagonal elements are set to zero:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "np.eye(5, dtype=int)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The `arange` function works like the `range` function, but produces an array instead of a list." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "np.arange(0,10,2)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "For non-integer ranges it is better to use `linspace`:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "np.linspace(0, np.pi, 5) # Evenly spaced range with 5 elements" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "With `linspace` one does not have to compute the length of the step, but instead one specifies the wanted number of elements. By default, the endpoint is included in the result, unlike with `arange`." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Arrays with random elements\n", "\n", "To test our programs we might use real data as input. However, real data is not always available, and it may take time to gather. We could instead generate random numbers to use as substitute. They can be generated really easily with NumPy, and can be sampled from several different distributions, of which we mention below only a few. Random data can simulate real data better than, for example, ranges or constant arrays. Sometimes we also need random numbers in our programs to choose a subset of real data (sampling). NumPy can easily produce arrays of wanted shape filled with random numbers. Below are few examples." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "np.random.random((3,4)) # Elements are uniformly distributed from half-open interval [0.0,1.0)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "np.random.normal(0, 1, (3,4)) # Elements are normally distributed with mean 0 and standard deviation 1" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "np.random.randint(-2, 10, (3,4)) # Elements are uniformly distributed integers from the half-open interval [-2,10)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Sometimes it is useful to be able to recreate exactly the same data in every run of our program. For example, if there is a bug in our program, which manifests itself only with certain input, then to debug our program it needs to behave deterministically. We can create random numbers deterministically, if we always start from the same starting point. This starting point is usually an integer, and we call it a *seed*. Example of use:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "np.random.seed(0)\n", "print(np.random.randint(0, 100, 10))\n", "print(np.random.normal(0, 1, 10))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If you run the above cell multiple times, it will always give the same numbers, unlike the earlier examples. Try rerunning them now!" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The call to `np.random.seed` initializes the *global* random number generator. The calls `np.random.random`, `np.random.normal`, etc all use this global random number generator. It is however possible to create new random number generators, and use those to sample random numbers from a distribution. Example on usage:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "new_generator = np.random.RandomState(seed=123) # RandomState is a class, so we give the seed to its constructor\n", "new_generator.randint(0, 100, 10)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You will see these used later in the materials and in the exercises, just so we can agree what the random input data is. How else could we agree whether result is correct or not, if we can't agree what the input is!" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Array types and attributes\n", "\n", "An array has several attributes: `ndim` tells the number of dimensions, `shape` tells the size in each dimension, `size` tells the number of elements, and `dtype` tells the element type. Let's create a helper function to explore these attributes:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def info(name, a):\n", " print(f\"{name} has dim {a.ndim}, shape {a.shape}, size {a.size}, and dtype {a.dtype}:\")\n", " print(a)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "b=np.array([[1,2,3], [4,5,6]])\n", "info(\"b\", b)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "c=np.array([b, b]) # Creates a 3-dimensional array\n", "info(\"c\", c)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "d=np.array([[1,2,3,4]]) # a row vector\n", "info(\"d\", d)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Note above how Python printed the three dimensional array. The general rules of printing an n-dimensional array as a nested list are:\n", "\n", "* the last dimension is printed from left to right,\n", "* the second-to-last is printed from top to bottom,\n", "* the rest are also printed from top to bottom, with each slice separated from the next by an empty line." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Indexing, slicing and reshaping" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Indexing\n", "One dimensional array behaves like the list in Python:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "a=np.array([1,4,2,7,9,5])\n", "print(a[1])\n", "print(a[-2])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "For multi-dimensional array the index is a comma separated tuple instead of a single integer:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "b=np.array([[1,2,3], [4,5,6]])\n", "print(b)\n", "print(b[1,2]) # row index 1, column index 2\n", "print(b[0,-1]) # row index 0, column index -1" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# As with lists, modification through indexing is possible\n", "b[0,0] = 10\n", "print(b)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Note that if you give only a single index to a multi-dimensional array, it indexes the first dimension of the array, that is the rows. For example:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(b[0]) # First row\n", "print(b[1]) # Second row" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Slicing\n", "Slicing works similarly to lists, but now we can have slices in different dimensions:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(a)\n", "print(a[1:3])\n", "print(a[::-1]) # Reverses the array" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(b)\n", "print(b[:,0])\n", "print(b[0,:])\n", "print(b[:,1:])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can even assign to a slice:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "b[:,1:] = 7\n", "print(b)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "A common idiom is to extract rows or columns from an array:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(b[:,0]) # First column\n", "print(b[1,:]) # Second row" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Reshaping\n", "\n", "When an array is reshaped, its number of elements stays the same, but they are reinterpreted to have a different shape. An example of this is to interpret a one dimensional array as two dimension array:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "a=np.arange(9)\n", "anew=a.reshape(3,3)\n", "info(\"anew\", anew)\n", "info(\"a\", a)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "d=np.arange(4) # 1d array\n", "dr=d.reshape(1,4) # row vector\n", "dc=d.reshape(4,1) # column vector\n", "info(\"d\", d)\n", "info(\"dr\", dr)\n", "info(\"dc\", dc)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "Note the 1d array and the row and column vectors, which are 2d arrays, are fundamentally different objects, even though they look similar. They behave differently when we combine or otherwise operate arrays of different shapes, as we shall see in the next section and later in this material.\n", "
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "An alternative syntax to create, for example, column or row vectors is through the `np.newaxis` keyword. Sometimes this is easier or more natural than with the `reshape` method:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "info(\"d\", d)\n", "info(\"drow\", d[:, np.newaxis])\n", "info(\"drow\", d[np.newaxis, :])\n", "info(\"dcol\", d[:, np.newaxis])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "####
Exercise 11 (rows and columns)
\n", "\n", "Write two functions, `get_rows` and `get_columns`, that get a two dimensional array as parameter.\n", "They should return the list of rows and columns of the array, respectively. The rows and columns should be one dimensional arrays. You may use the *transpose* operation, which flips rows to columns, in your solution. The transpose is done by the `T` method:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "a=np.random.randint(0, 10, (4,4))\n", "print(a)\n", "print(a.T)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Test your solution in the main function.\n", "Example of usage:\n", "```\n", "a = np.array([[5, 0, 3, 3],\n", " [7, 9, 3, 5],\n", " [2, 4, 7, 6],\n", " [8, 8, 1, 6]])\n", "get_rows(a)\n", "[array([5, 0, 3, 3]), array([7, 9, 3, 5]), array([2, 4, 7, 6]), array([8, 8, 1, 6])]\n", "get_columns(a)\n", "[array([5, 7, 2, 8]), array([0, 9, 4, 8]), array([3, 3, 7, 1]), array([3, 5, 6, 6])]\n", "```\n", "\n", "
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Array concatenation, splitting and stacking\n", "\n", "The are two ways of combining several arrays into one bigger array: `concatenate` and `stack`. `Concatenate` takes n-dimensional arrays and returns an n-dimensional array, whereas `stack` takes n-dimensional arrays and returns n+1-dimensional array. Few examples of these:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "a=np.arange(2)\n", "b=np.arange(2,5)\n", "print(f\"a has shape {a.shape}: {a}\")\n", "print(f\"b has shape {b.shape}: {b}\")\n", "np.concatenate((a,b)) # concatenating 1d arrays" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "c=np.arange(1,5).reshape(2,2)\n", "print(f\"c has shape {c.shape}:\", c, sep=\"\\n\")\n", "np.concatenate((c,c)) # concatenating 2d arrays" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "By default `concatenate` joins the arrays along axis 0. To join the arrays horizontally, add parameter `axis=1`:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "np.concatenate((c,c), axis=1)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If you want to catenate arrays with different dimensions, for example to add a new column to a 2d array, you must first reshape the arrays to have same number of dimensions:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(\"New row:\")\n", "print(np.concatenate((c,a.reshape(1,2))))\n", "print(\"New column:\")\n", "print(np.concatenate((c,a.reshape(2,1)), axis=1))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Use `stack` to create higher dimensional arrays from lower dimensional arrays:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "np.stack((b,b))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "np.stack((b,b), axis=1)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Inverse operation of `concatenate` is `split`. Its argument specifies either the number of equal parts the array is divided into, or it specifies explicitly the break points." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "d=np.arange(12).reshape(6,2)\n", "print(\"d:\")\n", "print(d)\n", "d1,d2 = np.split(d, 2)\n", "print(\"d1:\")\n", "print(d1)\n", "print(\"d2:\")\n", "print(d2)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "d=np.arange(12).reshape(2,6)\n", "print(\"d:\")\n", "print(d)\n", "parts=np.split(d, (2,3,5), axis=1)\n", "for i, p in enumerate(parts):\n", " print(\"part %i:\" % i)\n", " print(p)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "####
Exercise 12 (row and column vectors)
\n", "\n", "Create function `get_row_vectors` that returns a list of rows from the input array of shape `(n,m)`, but this time the rows must have shape `(1,m)`. Similarly, create function `get_columns_vectors` that returns a list of columns (each having shape `(n,1)`) of the input matrix .\n", "\n", "Example: for a 2x3 input matrix\n", "\n", "```\n", " [[5 0 3]\n", " [3 7 9]]\n", "```\n", "\n", "the result should be\n", "\n", "```\n", "Row vectors: \n", "[array([[5, 0, 3]]), array([[3, 7, 9]])]\n", "Column vectors: \n", "[array([[5],\n", " [3]]), \n", " array([[0],\n", " [7]]), \n", " array([[3],\n", " [9]])]\n", "```\n", "\n", "The above output is basically just the returned lists printed with `print`. Only some\n", "whitespace is adjusted to make it look nicer. Output is not tested.\n", "\n", "
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "####
Exercise 13 (diamond)
\n", "Create a function `diamond` that returns a two dimensional integer array where the `1`s form a diamond shape. Rest of the numbers are `0`. The function should get a parameter that tells the length of a side of the diamond. Do this using the `eye` and `concatenate` functions of NumPy and array slicing.\n", "\n", "Example of usage:\n", "```\n", "print(diamond(3))\n", "[[0 0 1 0 0]\n", " [0 1 0 1 0]\n", " [1 0 0 0 1]\n", " [0 1 0 1 0]\n", " [0 0 1 0 0]]\n", "print(diamond(1))\n", "[[1]]\n", "```" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Fast computation using universal functions\n", "\n", "In addition to providing a way to store and access multi-dimension arrays, NumPy also provides several routines to perform computations on them. One of the reasons for the popularity of NumPy is that these computations can be very efficient, much more efficient than what Python can normally do. The biggest bottle-necks in efficiency are the loops, which can be iterated millions, billions, or even more times. The loops should be as efficient as possible. What slows down loops in Python as the fact that Python is dynamically typed language. That means that at each expression Python has find out the types of the arguments of the operations. Let's consider the following loop:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "L=[1, 5.2, \"ab\"]\n", "L2=[]\n", "for x in L:\n", " L2.append(x*2)\n", "print(L2)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "At each iteration of this loop Python has find out the type of the variable x, which can in this example be an int, a float or a string, and depending on this type call a different function to perform the \"multiplication\" by two. What makes NumPy efficient, is the requirement that each element in an array must be of the same type. This homogeneity of arrays makes it possible to create *vectorized* operation, which don't operate on single elements, but on arrays (or subarrays). The previous example using vectorized operations of NumPy is shown below." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "a=np.array([2.1, 5.0, 17.2])\n", "a2=a*2\n", "print(a2)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Because each iteration is using identical operations only the data differs, this can compiled into machine language, and then performed in one go, hence avoiding Python's dynamic typing. The name vector operation comes from linear algebra where the addition of two vectors $v=(v_1,v_2, \\ldots, v_d)$ and $w=(w_1,w_2, \\ldots, w_d)$ is defined element-wise as $v+w = (v_1 + w_1,v_2 + w_2, \\ldots, v_d + w_d)$.\n", "\n", "In addition to addition there are several mathematical functions defined in the vector form. The basic arithmetic operations are: addition `+`, subtraction `-`, negation `-`, multiplication `*`, division `/`, floor division `//`, exponentation `**`, and remainder `%`. \n", "\n", "The can be combined into more complicated expressions. An example:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "b=np.array([-1, 3.2, 2.4])\n", "print(-a**2 * b)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Several other mathematical functions are defined as well. A few examples of these can be found below." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(np.abs(b))\n", "print(np.cos(b))\n", "print(np.exp(b))\n", "print(np.log2(np.abs(b)))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In NumPy nomenclature these vector operations are called *ufuncs* (universal functions)." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Aggregations: max, min, sum, mean, standard deviation...\n", "\n", "Aggregations allow us to condense the information in an array into just few numbers." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "np.random.seed(0)\n", "a=np.random.randint(-100, 100, (4,5))\n", "print(a)\n", "print(f\"Minimum: {a.min()}, maximum: {a.max()}\")\n", "print(f\"Sum: {a.sum()}\")\n", "print(f\"Mean: {a.mean()}, standard deviation: {a.std()}\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Instead of aggregating over the whole array, we can aggregate over certain axes only as well:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "np.random.seed(9)\n", "b=np.random.randint(0, 10, (3,4))\n", "print(b)\n", "print(\"Column sums:\", b.sum(axis=0))\n", "print(\"Row sums:\", b.sum(axis=1))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "![aggregation](aggregation.svg)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "Note that most of the aggregation functions in NumPy have corresponding methods. In addition, Python language has builtin functions `sum`, `min`, `max`, `any`, and `all` for sequences. Make sure you don't accidentally use these for arrays, since they may have slightly different semantics, and they will be significantly slower than NumPy's functions and methods.\n", "
\n", "\n", "| Python function | NumPy function | NumPy method |\n", "| ----- | -------------- | ------------ |\n", "| sum | np.sum | a.sum |\n", "| - | np.prod | a.prod |\n", "| - | np.mean | a.mean |\n", "| - | np.std | a.std |\n", "| - | np.var | a.var |\n", "| min | np.min | a.min |\n", "| max | np.max | a.max |\n", "| - | np.argmin | a.argmin |\n", "| - | np.argmax | a.argmax |\n", "| - | np.median | - |\n", "| - | np.percentile | - |\n", "| any | np.any | a.any |\n", "| all | np.all | a.all |\n", "\n", " " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let's measure how much slower Python's `sum` function is compared to NumPy's equivalent when aggregating over an array:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "a=np.arange(1000)\n", "%timeit np.sum(a)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "%timeit sum(a)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The speed of NumPy is partly due to the fact that its arrays must have same type for all the elements. This requirement allows some efficient optimizations." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "####
Exercise 14 (vector lengths)
\n", "\n", "Write function `vector_lengths` that gets a two dimensional array of shape (n,m) as a parameter. Each row in this array corresponds to a vector. The function should return an array of shape (n,), that has the length of each vector in the input. The length is defined by the usual \n", "[Euclidean norm](). Don't use loops at all in your solution. Instead use vectorized operations. You must use at least the `np.sum` and the `np.sqrt` functions. You can't use the function `scipy.linalg.norm`. Test your function in the main function." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "####
Exercise 15 (vector angles)
\n", "\n", "Let x and y be m-dimensional vectors. The angle $\\alpha$ between two vectors is defined by the equation\n", "$\\cos_{xy}(\\alpha):=\\frac{\\langle x,y\\rangle}{||x|| ||y||}$,\n", "where the angle brackets denote the [inner product](https://en.wikipedia.org/wiki/Inner_product_space#Euclidean_space), and $||x||:=\\sqrt{\\langle x,x \\rangle}$. \n", "\n", "Write function `vector_angles` that gets two arrays X and Y with same shape (n,m) as parameters. Each row in the arrays corresponds to a vector. The function should return vector of shape (n,) with the corresponding angles between vectors of `X` and `Y` in degrees, not in radians. Again, don't use loops, but use vectorized operations.\n", "\n", "Note: function `np.arccos` is only defined on the domain [-1.0,1.0]. If you try to compute `np.arccos(1.000000001)`, it will fail. These kind of errors can occur due to use of finite precision in numerical computations. Force the argument to be in the correct range (`clip` method).\n", "\n", "Test your solution in the main program.\n", "
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Broadcasting\n", "\n", "We have seen that NumPy allows array operations that are performed element-wise. But NumPy also allows binary operations that don't require the two arrays to have the same shape. For example, we can add 4 to all elements of an array with the following expression:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "np.arange(3) + np.array([4])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In fact, because an array with only one element, say 4, can be thought of as a scalar 4, NumPy allows the following expression, which is equivalent to the above:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "np.arange(3) + 4" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "To get can idea of what operations are allowed, i.e. what shapes of the two arrays are *compatible*, it can be useful to think that before the binary operation is performed, NumPy tries to stretch the arrays to have the same shape. For example in above NumPy first stretched the array `np.array([4])` (or the scalar 4), to the array `np.array([4,4,4])` and then performed the element-wise addition. In NumPy this stretching is called *broadcasting*.\n", "\n", "![broadcast](broadcast.svg)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The argument arrays can of course have higher dimensions, as the next example shows:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "a=np.full((3,3), 5)\n", "b=np.arange(3)\n", "print(\"a:\", a, sep=\"\\n\")\n", "print(\"b:\", b)\n", "print(\"a+b:\", a+b, sep=\"\\n\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In this example the second argument was first broadcasted to the array" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "np.array([[0, 1, 2],\n", " [0, 1, 2],\n", " [0, 1, 2]])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "and then the addition was performed. And it may be that both of the argument arrays need to be broadcasted as in the next example:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "a=np.arange(3)\n", "b=np.arange(3).reshape((3,1))\n", "info(\"a\", a)\n", "info(\"b\", b)\n", "info(\"a+b\", a+b)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "To see what the arguments were broadcasted to before the binary operation, the function `np.broadcast_arrays` can be used:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "broadcasted_a, broadcasted_b = np.broadcast_arrays(a,b)\n", "info(\"broadcasted_a\", broadcasted_a)\n", "info(\"broadcasted_b\", broadcasted_b)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "So, both arrays were broadcasted, but in different ways. Let's next go through the [rules](https://docs.scipy.org/doc/numpy-1.14.0/reference/ufuncs.html#broadcasting) how the broadcasting work.\n", "\n", "\n", "1. All input arrays with `ndim` smaller than the input array of largest `ndim`, have 1’s prepended to their shapes.\n", "2. The size in each dimension of the output shape is the maximum of all the input sizes in that dimension.\n", "3. An input can be used in the calculation if its size in a particular dimension either matches the output size in that dimension, or has value exactly 1.\n", "4. If an input has a dimension size of 1 in its shape, the first data entry in that dimension will be used for all calculations along that dimension. In other words, the stepping machinery of the ufunc will simply not step along that dimension (the stride will be 0 for that dimension).\n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Finally an example of a situation where the two array are not compatible:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "a=np.array([1,2,3])\n", "b=np.array([4,5])\n", "try:\n", " a+b # This does not work since it violates the rule 3 above.\n", "except ValueError as e:\n", " import sys\n", " print(e, file=sys.stderr)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "####
Exercise 16 (multiplication table revisited)
\n", "Write function `multiplication_table` that gets a positive integer `n` as parameter. The function should return an array with shape (n,n). The element at index `(i,j)` should be `i*j`. Don't use `for` loops! In your solution, rely on broadcasting, the `np.arange` function, reshaping and vectorized operators. Example of usage:\n", "```\n", "print(multiplication_table(4))\n", "[[0 0 0 0]\n", " [0 1 2 3]\n", " [0 2 4 6]\n", " [0 3 6 9]]\n", "```\n", "
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Summary (week 2)\n", "\n", "* We have learned how regular expressions can be used to specify regular sets of strings\n", "\n", " * We know how to find out if a string matches a regular expression\n", " * We know how to extract pieces of text that match a RE\n", " * We can replace matches to a RE with another string\n", "* We can read (and write) a text file either line by line or whole file at the same time\n", "* We also know how to specify the encoding of the file. The utf-8 encoding is a very common and can represent nearly every character or symbol of any (natural) language\n", "* Program's parameters are in the array `sys.argv`, and we can return a value from the program with the function `sys.exit`\n", "* The file streams `sys.stdin`, `sys.stdout`, and `sys.stderr` allow basic textual input and output to and from the program\n", "* Every value in Python is an object\n", " * Classes are user defined data types, they tell how to construct instances (objects) of that type\n", " * Relationship between objects and classes: `isinstance`\n", " * Relationship between classes: `issubclass`\n", "* Exceptions signal exceptional situations, not necessarily errors\n", " * We know how catch and raise exceptions\n", "* The efficiency of NumPy is based on the fact that the same operations can be performed on elements fast, if\n", "all the elements have the same type. These are called vectorized operations\n", "* We know how to create, reshape, perform basic access, combine, split, and aggregate arrays" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "\n", "\n", "\"Open\n" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "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.6.8" }, "varInspector": { "cols": { "lenName": 16, "lenType": 16, "lenVar": 40 }, "kernels_config": { "python": { "delete_cmd_postfix": "", "delete_cmd_prefix": "del ", "library": "var_list.py", "varRefreshCmd": "print(var_dic_list())" }, "r": { "delete_cmd_postfix": ") ", "delete_cmd_prefix": "rm(", "library": "var_list.r", "varRefreshCmd": "cat(var_dic_list()) " } }, "types_to_exclude": [ "module", "function", "builtin_function_or_method", "instance", "_Feature" ], "window_display": false } }, "nbformat": 4, "nbformat_minor": 2 }