{ "metadata": { "name": "", "signature": "sha256:c320db1f9e67f49f604975c321ab723db6b6d429cebb93f390129c1d7e3e6366" }, "nbformat": 3, "nbformat_minor": 0, "worksheets": [ { "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Featured Recipe #1: Getting the Best Performance out of NumPy" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "> This is the first featured recipe from the [**IPython Cookbook**](http://ipython-books.github.io/), the definitive guide to **high-performance scientific computing** and **data science** in Python." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**NumPy** is the cornerstone of the scientific Python software stack. It provides a special data type optimized for vector computations, the `ndarray`. This object is at the core of most algorithms in scientific numerical computing.\n", "\n", "With NumPy arrays, you can achieve significant performance speedups over native Python, particularly when your computations follow the ***Single Instruction, Multiple Data* (SIMD)** paradigm. However, it is also possible to unintentionally write non-optimized code with NumPy.\n", "\n", "In this featured recipe, we will see some tricks that can help you write optimized NumPy code. We will start by looking at ways to avoid unnecessary array copies in order to save time and memory. In that respect, we will need to dig into the internals of NumPy." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Learning to avoid unnecessary array copies" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Computations with NumPy arrays may involve internal copies between blocks of memory. These copies are not always necessary, in which case they should be avoided. Here are a few tips that can help you optimize your code accordingly." ] }, { "cell_type": "code", "collapsed": false, "input": [ "import numpy as np" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 2 }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Inspect the memory address of arrays" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "1.\tThe first step when looking for silent array copies is to find out the location of arrays in memory. The following function does just that:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "def id(x):\n", " # This function returns the memory\n", " # block address of an array.\n", " return x.__array_interface__['data'][0]" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 3 }, { "cell_type": "markdown", "metadata": {}, "source": [ "2.\tYou may sometimes need to make a copy of an array, for instance if you need to manipulate an array while keeping an original copy in memory." ] }, { "cell_type": "code", "collapsed": false, "input": [ "a = np.zeros(10); aid = id(a); aid" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 4, "text": [ "71211328" ] } ], "prompt_number": 4 }, { "cell_type": "code", "collapsed": false, "input": [ "b = a.copy(); id(b) == aid" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 5, "text": [ "False" ] } ], "prompt_number": 5 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Two arrays with the same data location (as returned by `id`) share the underlying data buffer. However, the opposite is only true if the arrays have the same **offset** (meaning that they have the same first element). Two shared arrays with different offsets will have slightly different memory locations, as shown in the following example:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "id(a), id(a[1:])" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 6, "text": [ "(71211328, 71211336)" ] } ], "prompt_number": 6 }, { "cell_type": "markdown", "metadata": {}, "source": [ "In this recipe, we'll make sure to use this method with arrays that have the same offset. Here is a more reliable solution for finding out if two arrays share the same data:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "def get_data_base(arr):\n", " \"\"\"For a given Numpy array, finds the\n", " base array that \"owns\" the actual data.\"\"\"\n", " base = arr\n", " while isinstance(base.base, np.ndarray):\n", " base = base.base\n", " return base\n", "\n", "def arrays_share_data(x, y):\n", " return get_data_base(x) is get_data_base(y)" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 7 }, { "cell_type": "code", "collapsed": false, "input": [ "print(arrays_share_data(a,a.copy()),\n", " arrays_share_data(a,a[1:]))" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "False True\n" ] } ], "prompt_number": 8 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Thanks to [Michael Droettboom](https://github.com/ipython-books/cookbook-code/issues/2) for pointing out this precision and proposing this alternative solution." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### In-place and implicit copy operations" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "3.\tArray computations can involve in-place operations (first example below: the array is modified) or implicit-copy operations (second example: a new array is created)." ] }, { "cell_type": "code", "collapsed": false, "input": [ "a *= 2; id(a) == aid" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 5, "text": [ "True" ] } ], "prompt_number": 5 }, { "cell_type": "code", "collapsed": false, "input": [ "c = a * 2; id(c) == aid" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 6, "text": [ "False" ] } ], "prompt_number": 6 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Be sure to choose the type of operation you actually need. Implicit-copy operations are significantly slower, as shown here:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "%%timeit a = np.zeros(10000000)\n", "a *= 2" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "10 loops, best of 3: 19.2 ms per loop\n" ] } ], "prompt_number": 7 }, { "cell_type": "code", "collapsed": false, "input": [ "%%timeit a = np.zeros(10000000)\n", "b = a * 2" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "10 loops, best of 3: 42.6 ms per loop\n" ] } ], "prompt_number": 8 }, { "cell_type": "markdown", "metadata": {}, "source": [ "4.\tReshaping an array may or may not involve a copy. The reasons will be explained below. For instance, reshaping a 2D matrix does not involve a copy, unless it is transposed (or more generally non-contiguous):" ] }, { "cell_type": "code", "collapsed": false, "input": [ "a = np.zeros((10, 10)); aid = id(a); aid" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 9, "text": [ "53423728" ] } ], "prompt_number": 9 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Reshaping an array while preserving its order does not trigger a copy." ] }, { "cell_type": "code", "collapsed": false, "input": [ "b = a.reshape((1, -1)); id(b) == aid" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 10, "text": [ "True" ] } ], "prompt_number": 10 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Transposing an array changes its order so that a reshape triggers a copy." ] }, { "cell_type": "code", "collapsed": false, "input": [ "c = a.T.reshape((1, -1)); id(c) == aid" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 11, "text": [ "False" ] } ], "prompt_number": 11 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Therefore, the latter instruction will be significantly slower than the former." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "5.\tThe flatten and ravel methods of an array reshape it into a 1D vector (flattened array). The former method always returns a copy, whereas the latter returns a copy only if necessary (so it's significantly faster too, especially with large arrays)." ] }, { "cell_type": "code", "collapsed": false, "input": [ "d = a.flatten(); id(d) == aid" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 12, "text": [ "False" ] } ], "prompt_number": 12 }, { "cell_type": "code", "collapsed": false, "input": [ "e = a.ravel(); id(e) == aid" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 13, "text": [ "True" ] } ], "prompt_number": 13 }, { "cell_type": "code", "collapsed": false, "input": [ "%timeit a.flatten()" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "1000000 loops, best of 3: 881 ns per loop\n" ] } ], "prompt_number": 14 }, { "cell_type": "code", "collapsed": false, "input": [ "%timeit a.ravel()" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "1000000 loops, best of 3: 294 ns per loop\n" ] } ], "prompt_number": 15 }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Broadcasting rules" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "6. **Broadcasting rules** allow you to make computations on arrays with different but compatible shapes. In other words, you don't always need to reshape or tile your arrays to make their shapes match. The following example illustrates two ways of doing an outer product between two vectors: the first method involves array tiling, the second one involves broadcasting. The last method is significantly faster." ] }, { "cell_type": "code", "collapsed": false, "input": [ "n = 1000" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 16 }, { "cell_type": "code", "collapsed": false, "input": [ "a = np.arange(n)\n", "ac = a[:, np.newaxis]\n", "ar = a[np.newaxis, :]" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 17 }, { "cell_type": "code", "collapsed": false, "input": [ "%timeit np.tile(ac, (1, n)) * np.tile(ar, (n, 1))" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "100 loops, best of 3: 10 ms per loop\n" ] } ], "prompt_number": 18 }, { "cell_type": "code", "collapsed": false, "input": [ "%timeit ar * ac" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "100 loops, best of 3: 2.36 ms per loop\n" ] } ], "prompt_number": 19 }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Making efficient selections in arrays with NumPy" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "NumPy offers multiple ways of selecting slices of arrays. Array views refer to the original data buffer of an array, but with different offsets, shapes and strides. They only permit strided selections (i.e. with linearly spaced indices). NumPy also offers specific functions to make arbitrary selections along one axis. Finally, fancy indexing is the most general selection method, but it is also the slowest as we will see in this recipe. Faster alternatives should be chosen when possible." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "1.\tLet's create an array with a large number of rows. We will select slices of this array along the first dimension." ] }, { "cell_type": "code", "collapsed": false, "input": [ "n, d = 100000, 100" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 23 }, { "cell_type": "code", "collapsed": false, "input": [ "a = np.random.random_sample((n, d)); aid = id(a)" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 24 }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Array views and fancy indexing" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "2.\tLet's select one every ten rows, using two different methods (array view and fancy indexing)." ] }, { "cell_type": "code", "collapsed": false, "input": [ "b1 = a[::10]\n", "b2 = a[np.arange(0, n, 10)]" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 25 }, { "cell_type": "code", "collapsed": false, "input": [ "np.array_equal(b1, b2)" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 26, "text": [ "True" ] } ], "prompt_number": 26 }, { "cell_type": "markdown", "metadata": {}, "source": [ "3.\tThe view refers to the original data buffer, whereas fancy indexing yields a copy." ] }, { "cell_type": "code", "collapsed": false, "input": [ "id(b1) == aid, id(b2) == aid" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 27, "text": [ "(True, False)" ] } ], "prompt_number": 27 }, { "cell_type": "markdown", "metadata": {}, "source": [ "4.\tLet's compare the performance of both methods." ] }, { "cell_type": "code", "collapsed": false, "input": [ "%timeit a[::10]" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "1000000 loops, best of 3: 804 ns per loop\n" ] } ], "prompt_number": 28 }, { "cell_type": "code", "collapsed": false, "input": [ "%timeit a[np.arange(0, n, 10)]" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "100 loops, best of 3: 14.1 ms per loop\n" ] } ], "prompt_number": 29 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Fancy indexing is several orders of magnitude slower as it involves copying a large array." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Alternatives to fancy indexing: list of indices" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "5.\tWhen non-strided selections need to be done along one dimension, array views are not an option. However, alternatives to fancy indexing still exist in this case. Given a list of indices, NumPy's function take performs a selection along one axis." ] }, { "cell_type": "code", "collapsed": false, "input": [ "i = np.arange(0, n, 10)" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 30 }, { "cell_type": "code", "collapsed": false, "input": [ "b1 = a[i]\n", "b2 = np.take(a, i, axis=0)" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 31 }, { "cell_type": "code", "collapsed": false, "input": [ "np.array_equal(b1, b2)" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 32, "text": [ "True" ] } ], "prompt_number": 32 }, { "cell_type": "markdown", "metadata": {}, "source": [ "The second method is faster:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "%timeit a[i]" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "100 loops, best of 3: 13 ms per loop\n" ] } ], "prompt_number": 33 }, { "cell_type": "code", "collapsed": false, "input": [ "%timeit np.take(a, i, axis=0)" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "100 loops, best of 3: 4.87 ms per loop\n" ] } ], "prompt_number": 34 }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Alternatives to fancy indexing: mask of booleans" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "6.\tWhen the indices to select along one axis are specified by a vector of boolean masks, the function `compress` is an alternative to fancy indexing." ] }, { "cell_type": "code", "collapsed": false, "input": [ "i = np.random.random_sample(n) < .5" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 35 }, { "cell_type": "markdown", "metadata": {}, "source": [ "The selection can be made using fancy indexing or the `np.compress` function." ] }, { "cell_type": "code", "collapsed": false, "input": [ "b1 = a[i]\n", "b2 = np.compress(i, a, axis=0)" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 36 }, { "cell_type": "code", "collapsed": false, "input": [ "np.array_equal(b1, b2)" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 37, "text": [ "True" ] } ], "prompt_number": 37 }, { "cell_type": "code", "collapsed": false, "input": [ "%timeit a[i]" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "10 loops, best of 3: 59.8 ms per loop\n" ] } ], "prompt_number": 38 }, { "cell_type": "code", "collapsed": false, "input": [ "%timeit np.compress(i, a, axis=0)" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "10 loops, best of 3: 24.1 ms per loop\n" ] } ], "prompt_number": 39 }, { "cell_type": "markdown", "metadata": {}, "source": [ "The second method is also significantly faster than fancy indexing." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Fancy indexing is the most general way of making completely arbitrary selections of an array. However, more specific and faster methods often exist and should be preferred when possible.\n", "\n", "Array views should be used whenever strided selections have to be done, but one needs to be careful about the fact that views refer to the original data buffer." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## How it works?" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In this section, we will see what happens under the hood when using NumPy, and how this knowledge allows us to understand the tricks given in this recipe." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Why are NumPy arrays efficient?" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "A NumPy array is basically described by metadata (number of dimensions, shape, data type, and so on) and the actual data. The data is stored in a homogeneous and contiguous block of memory, at a particular address in system memory (*Random Access Memory*, or RAM). This block of memory is called the **data buffer**. This is the main difference with a pure Python structure, like a list, where the items are scattered across the system memory. This aspect is the critical feature that makes NumPy arrays so efficient.\n", "\n", "Why is this so important? Here are the main reasons:" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "1.\t**Array computations can be written very efficiently in a low-level language like C** (and a large part of NumPy is actually written in C). Knowing the address of the memory block and the data type, it is just simple arithmetic to loop over all items, for example. There would be a significant overhead to do that in Python with a list.\n", "\n", "2.\t**Spatial locality in memory access patterns** results in significant performance gains, notably thanks to the CPU cache. Indeed, the cache loads bytes in chunks from RAM to the CPU registers. Adjacent items are then loaded very efficiently (sequential locality, or locality of reference).\n", "\n", "3.\t**Data elements are stored contiguously in memory**, so that NumPy can take advantage of vectorized instructions on modern CPUs, like Intel's SSE and AVX, AMD's XOP, and so on. For example, multiple consecutive floating point numbers can be loaded in 128, 256 or 512 bits registers for vectorized arithmetical computations implemented as CPU instructions." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Additionally, let's mention the fact that NumPy can be linked to highly optimized linear algebra libraries like *BLAS* and *LAPACK*, for example through the *Intel Math Kernel Library (MKL)*. A few specific matrix computations may also be multithreaded, taking advantage of the power of modern multicore processors." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In conclusion, **storing data in a contiguous block of memory ensures that the architecture of modern CPUs is used optimally, in terms of memory access patterns, CPU cache, and vectorized instructions**." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### What is the difference between in-place and implicit-copy operations?" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let's explain trick 3. An expression like `a *= 2` corresponds to an in-place operation, where all values of the array are multiplied by two. By contrast, `a = a * 2` means that a new array containing the values of `a * 2` is created, and the variable a now points to this new array. The old array becomes unreferenced and will be deleted by the garbage collector. No memory allocation happens in the first case, contrary to the second case." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "More generally, expressions like `a[i:j]` are views to parts of an array: they point to the memory buffer containing the data. Modifying them with in-place operations changes the original array. Hence, `a[:] = a * 2` results in an in-place operation, unlike `a = a * 2`." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Knowing this subtlety of NumPy can help you fix some bugs (where an array is implicitly and unintentionally modified because of an operation on a view), and optimize the speed and memory consumption of your code by reducing the number of unnecessary copies." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Why cannot some arrays be reshaped without a copy?" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We explain here trick 4, where a transposed 2D matrix cannot be flattened without a copy. A 2D matrix contains items indexed by two numbers (row and column), but it is stored internally as a 1D contiguous block of memory, accessible with a single number. There is more than one way of storing matrix items in a 1D block of memory: we can put the elements of the first row first, the second row then, and so on, or the elements of the first column first, the second column then, and so on. The first method is called row-major order, whereas the latter is called column-major order. Choosing between the two methods is only a matter of internal convention: NumPy uses the row-major order, like C, but unlike FORTRAN." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "![Array layout](images/layout.png)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "More generally, NumPy uses the notion of **strides** to convert between a multidimensional index and the memory location of the underlying (1D) sequence of elements. The specific mapping between `array[i1, i2]` and the relevant byte address of the internal data is given by\n", "\n", "``\n", "offset = array.strides[0] * i1 + array.strides[1] * i2\n", "``\n", "\n", "When reshaping an array, NumPy avoids copies when possible by modifying the ``strides`` attribute. For example, when transposing a matrix, the order of ``strides`` is reversed, but the underlying data remains identical. However, flattening a transposed array cannot be accomplished simply by modifying ``strides`` (try it!), so a copy is needed (thanks to [Chris Beaumont](http://chrisbeaumont.org/) from Harvard for clarifying an earlier version of this paragraph).\n", "\n", "[Recipe 4.6](http://nbviewer.ipython.org/github/ipython-books/cookbook-code/blob/master/notebooks/chapter04_optimization/06_stride_tricks.ipynb) (*Using stride tricks with NumPy*) contains a more extensive discussion on strides. Also, [recipe 4.7](http://nbviewer.ipython.org/github/ipython-books/cookbook-code/blob/master/notebooks/chapter04_optimization/07_rolling_average.ipynb) (*Implementing an efficient rolling average algorithm with stride tricks*) shows how one can use strides to accelerate particular array computations." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Internal array layout can also explain some unexpected performance discrepancies between very similar NumPy operations. As a small exercise, can you explain the following benchmarks?" ] }, { "cell_type": "code", "collapsed": false, "input": [ "a = np.random.rand(5000, 5000)\n", "%timeit a[0,:].sum()\n", "%timeit a[:,0].sum()" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "100000 loops, best of 3: 9.57 \u00b5s per loop\n", "10000 loops, best of 3: 68.3 \u00b5s per loop" ] }, { "output_type": "stream", "stream": "stdout", "text": [ "\n" ] } ], "prompt_number": 40 }, { "cell_type": "markdown", "metadata": {}, "source": [ "### What are NumPy broadcasting rules?" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Broadcasting rules describe how arrays with different dimensions and/or shapes can still be used for computations. The general rule is that two dimensions are compatible when they are equal, or when one of them is 1. NumPy uses this rule to compare the shapes of the two arrays element-wise, starting with the trailing dimensions and working its way forward. The smallest dimension is internally stretched to match the other dimension, but this operation does not involve any memory copy." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## References\n", "\n", "Here are a few references:\n", "\n", "* [NumPy performance tricks](http://cyrille.rossant.net/numpy-performance-tricks/).\n", "* [Locality of reference](http://en.wikipedia.org/wiki/Locality_of_reference).\n", "* [Internals of NumPy in the SciPy lectures notes](http://scipy-lectures.github.io/advanced/advanced_numpy/).\n", "* [100 NumPy exercices](http://www.loria.fr/~rougier/teaching/numpy.100/index.html).\n", "* [Broadcasting rules and examples](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html).\n", "* [Array interface in NumPy](http://docs.scipy.org/doc/numpy/reference/arrays.interface.html).\n", "* [The complete list of NumPy routines is available on the NumPy Reference Guide](http://docs.scipy.org/doc/numpy/reference/).\n", "* [List of indexing routines](http://docs.scipy.org/doc/numpy/reference/routines.indexing.html)." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You will find related recipes on the [book's repository](https://github.com/ipython-books/cookbook-code)." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "> This was a featured recipe from the [IPython Cookbook](http://ipython-books.github.io/), by [Cyrille Rossant](http://cyrille.rossant.net), Packt Publishing, 2014." ] } ], "metadata": {} } ] }