NumPy


NumPy or sometimes ) is a library for the Python programming language, adding support for large, multi-dimensional arrays and matrices, along with a large collection of high-level mathematical functions to operate on these arrays. The ancestor of NumPy, Numeric, was originally created by Jim Hugunin with contributions from several other developers. In 2005, Travis Oliphant created NumPy by incorporating features of the competing Numarray into Numeric, with extensive modifications. NumPy is open-source software and has many contributors.

History

The Python programming language was not originally designed for numerical computing, but attracted the attention of the scientific and engineering community early on. In 1995 the special interest group matrix-sig was founded with the aim of defining an array computing package; among its members was Python designer and maintainer Guido van Rossum, who extended Python's syntax to make array computing easier.
An implementation of a matrix package was completed by Jim Fulton, then generalized by Jim Hugunin and called Numeric.
Hugunin, a graduate student at the Massachusetts Institute of Technology, joined the Corporation for National Research Initiatives in 1997 to work on JPython, leaving Paul Dubois of Lawrence Livermore National Laboratory to take over as maintainer. Other early contributors include David Ascher, Konrad Hinsen and Travis Oliphant.
A new package called Numarray was written as a more flexible replacement for Numeric. Like Numeric, it too is now deprecated. Numarray had faster operations for large arrays, but was slower than Numeric on small ones, so for a time both packages were used in parallel for different use cases. The last version of Numeric was released on 11 November 2005, while the last version of numarray was released on 24 August 2006.
There was a desire to get Numeric into the Python standard library, but Guido van Rossum decided that the code was not maintainable in its state then.
In early 2005, NumPy developer Travis Oliphant wanted to unify the community around a single array package and ported Numarray's features to Numeric, releasing the result as NumPy 1.0 in 2006. This new project was part of SciPy. To avoid installing the large SciPy package just to get an array object, this new package was separated and called NumPy. Support for Python 3 was added in 2011 with NumPy version 1.5.0.
In 2011, PyPy started development on an implementation of the NumPy API for PyPy. It is not yet fully compatible with NumPy.

Features

NumPy targets the CPython reference implementation of Python, which is a non-optimizing bytecode interpreter. Mathematical algorithms written for this version of Python often run much slower than compiled equivalents. NumPy addresses the slowness problem partly by providing multidimensional arrays and functions and operators that operate efficiently on arrays, requiring rewriting some code, mostly inner loops, using NumPy.
Using NumPy in Python gives functionality comparable to MATLAB since they are both interpreted, and they both allow the user to write fast programs as long as most operations work on arrays or matrices instead of scalars. In comparison, MATLAB boasts a large number of additional toolboxes, notably Simulink, whereas NumPy is intrinsically integrated with Python, a more modern and complete programming language. Moreover, complementary Python packages are available; SciPy is a library that adds more MATLAB-like functionality and Matplotlib is a plotting package that provides MATLAB-like plotting functionality. Internally, both MATLAB and NumPy rely on BLAS and LAPACK for efficient linear algebra computations.
Python bindings of the widely used computer vision library OpenCV utilize NumPy arrays to store and operate on data.
Since images with multiple channels are simply represented as three-dimensional arrays, indexing, or masking with other arrays are very efficient ways to access specific pixels of an image.
The NumPy array as universal data structure in OpenCV for images, extracted feature points, filter kernels and many more vastly simplifies the programming workflow and debugging.

The ndarray data structure

The core functionality of NumPy is its "ndarray", for n-dimensional array, data structure. These arrays are strided views on memory. In contrast to Python's built-in list data structure, these arrays are homogeneously typed: all elements of a single array must be of the same type.
Such arrays can also be views into memory buffers allocated by C/C++, Cython, and Fortran extensions to the CPython interpreter without the need to copy data around, giving a degree of compatibility with existing numerical libraries. This functionality is exploited by the SciPy package, which wraps a number of such libraries. NumPy has built-in support for memory-mapped ndarrays.

Limitations

Inserting or appending entries to an array is not as trivially possible as it is with Python's lists.
The np.pad routine to extend arrays actually creates new arrays of the desired shape and padding values, copies the given array into the new one and returns it.
NumPy's np.concatenate operation does not actually link the two arrays but returns a new one, filled with the entries from both given arrays in sequence.
Reshaping the dimensionality of an array with np.reshape is only possible as long as the number of elements in the array does not change.
These circumstances originate from the fact that NumPy's arrays must be views on contiguous memory buffers. A replacement package called Blaze attempts to overcome this limitation.
Algorithms that are not expressible as a vectorized operation will typically run slowly because they must be implemented in "pure Python", while vectorization may increase memory complexity of some operations from constant to linear, because temporary arrays must be created that are as large as the inputs. Runtime compilation of numerical code has been implemented by several groups to avoid these problems; open source solutions that interoperate with NumPy include scipy.weave, numexpr and Numba. Cython and Pythran are static-compiling alternatives to these.

Examples

;Array creation

>>> import numpy as np
>>> x = np.array
>>> x
array
>>> y = np.arange # like Python's list, but returns an array
>>> y
array

;Basic operations

>>> a = np.array
>>> b = np.linspace # create an array with four equally spaced points starting with 0 and ending with 2.
>>> c = a - b
>>> c
array
>>> a**2
array

;Universal functions

>>> a = np.linspace
>>> b = np.sin
>>> c = np.cos

;Linear algebra

>>> from numpy.random import rand
>>> from numpy.linalg import solve, inv
>>> a = np.array
>>> a.transpose
array
>>> inv
array
>>> b = np.array
>>> solve # solve the equation ax = b
array
>>> c = rand * 20 # create a 3x3 random matrix of values within scaled by 20
>>> c
array
>>> np.dot # matrix multiplication
array
>>> a @ c # Starting with Python 3.5 and NumPy 1.10
array

; Tensors

>>> M = np.zeros
>>> T = np.transpose
>>> T.shape

;Incorporation with OpenCV

>>> import numpy as np
>>> import cv2
>>> r = np.reshape%256,) # 256x256 pixel array with a horizontal gradient from 0 to 255 for the red color channel
>>> g = np.zeros_like # array of same size and type as r but filled with 0s for the green color channel
>>> b = r.T # transposed r will give a vertical gradient for the blue color channel
>>> cv2.imwrite # OpenCV images are interpreted as BGR, the depth-stacked array will be written to an 8bit RGB PNG-file called 'gradients.png'
True

;Nearest Neighbor Search - Iterative Python algorithm and vectorized NumPy version

>>> # # # Pure iterative Python # # #
>>> points = 9,2,8],,,,,,,,,
>>> minIdx = -1
>>> minDist = -1
>>> for idx, point in enumerate: # iterate over all points
dist = sum**2 for dp,dq in zip**0.5 # compute the euclidean distance for each point to q
if dist < minDist or minDist < 0: # if necessary, update minimum distance and index of the corresponding point
minDist = dist
minIdx = idx
>>> print
Nearest point to q:
>>> # # # Equivalent NumPy vectorization # # #
>>> import numpy as np
>>> points = np.array
>>> qPoint = np.array
>>> minIdx = np.argmin # compute all euclidean distances at once and return the index of the smallest one
>>> print
Nearest point to q: