The numpy
package (module) is used in almost all numerical computation using Python. It is a package that provide high-performance vector, matrix and higher-dimensional data structures for Python. It is implemented in C and Fortran so when calculations are vectorized (formulated with vectors and matrices), performance is very good.
NumPy
adds basic MATLAB-like capability to Python:
SciPy
builds on NumPy
(much like MATLAB toolboxes) adding:
Matplotlib
adds MATLAB-like plotting capability on top of NumPy
.
In [1]:
from pylab import *
In [2]:
import numpy as np
import scipy as sp
import matplotlib as mpl
import matplotlib.pyplot as plt
Some different ways of working with NumPy
are:
In [3]:
from numpy import eye, array # Import only what you need
from numpy.linalg import svd
In the numpy
package the terminology used for vectors, matrices and higher-dimensional data sets is array. There are a number of ways to initialize new numpy arrays, for example from
arange
, linspace
, etc.For example, to create new vector and matrix arrays from Python lists we can use the numpy.array
function.
In [4]:
# a vector: the argument to the array function is a Python list
v = array([1,2,3,4])
v
Out[4]:
In [5]:
# a matrix: the argument to the array function is a nested Python list
M = array([[1, 2], [3, 4]])
M
Out[5]:
The v
and M
objects are both of the type ndarray
that the numpy
module provides.
In [6]:
type(v), type(M)
Out[6]:
The difference between the v
and M
arrays is only their shapes. We can get information about the shape of an array by using the ndarray.shape
property.
In [7]:
v.shape
Out[7]:
In [8]:
M.shape
Out[8]:
The number of elements in the array is available through the ndarray.size
property:
In [9]:
M.size
Out[9]:
Equivalently, we could use the function numpy.shape
and numpy.size
In [10]:
shape(M)
Out[10]:
In [11]:
size(M)
Out[11]:
The number of dimensions of the array is available through the ndarray.ndim
property:
In [12]:
v.ndim
Out[12]:
In [13]:
M.ndim
Out[13]:
So far the numpy.ndarray
looks awefully much like a Python list (or nested list). Why not simply use Python lists for computations instead of creating a new array type?
There are several reasons:
numpy
arrays can be implemented in a compiled language (C and Fortran is used).Using the dtype
(data type) property of an ndarray
, we can see what type the data of an array has:
In [14]:
M.dtype
Out[14]:
We get an error if we try to assign a value of the wrong type to an element in a numpy array:
In [15]:
M[0,0] = "hello"
For larger arrays it is inpractical to initialize the data manually, using explicit python lists. Instead we can use one of the many functions in numpy
that generate arrays of different forms. Some of the more common are:
In [16]:
# create a range
x = arange(0, 10, 1) # arguments: start, stop, step
x
Out[16]:
In [17]:
x = arange(-1, 1, 0.1)
x
Out[17]:
In [18]:
# using linspace, both end points ARE included
linspace(0, 10, 25)
Out[18]:
In [19]:
logspace(0, 10, 10, base=e)
Out[19]:
In [20]:
x, y = mgrid[0:5, 0:5] # similar to meshgrid in MATLAB
In [21]:
x
Out[21]:
In [22]:
y
Out[22]:
In [23]:
# a diagonal matrix
diag([1,2,3])
Out[23]:
In [24]:
# diagonal with offset from the main diagonal
diag([1,2,3], k=1)
Out[24]:
In [25]:
zeros((3,3))
Out[25]:
In [26]:
ones((3,3))
Out[26]:
In [27]:
zeros_like(x)
Out[27]:
In [28]:
ones_like(x)
Out[28]:
We can index elements in an array using square brackets and indices:
In [29]:
# v is a vector, and has only one dimension, taking one index
v[0]
Out[29]:
In [30]:
# M is a matrix, or a 2 dimensional array, taking two indices
M[1,1]
Out[30]:
If we omit an index of a multidimensional array it returns the whole row (or, in general, a N-1 dimensional array)
In [31]:
M
Out[31]:
In [32]:
M[1]
Out[32]:
The same thing can be achieved with using :
instead of an index:
In [33]:
M[1,:] # row 1
Out[33]:
In [34]:
M[:,1] # column 1
Out[34]:
We can assign new values to elements in an array using indexing:
In [35]:
M[0,0] = -1
In [36]:
M
Out[36]:
In [37]:
# also works for rows and columns
M[0,:] = 0
M[:,1] = -1
In [38]:
M
Out[38]:
Index slicing is the technical name for the syntax M[lower:upper:step]
to extract part of an array:
In [39]:
A = array([1,2,3,4,5])
A
Out[39]:
In [40]:
A[1:3]
Out[40]:
Array slices are mutable: if they are assigned a new value the original array from which the slice was extracted is modified:
In [41]:
A[1:3] = [-2,-3]
A
Out[41]:
We can omit any of the three parameters in M[lower:upper:step]
:
In [42]:
A[::] # lower, upper, step all take the default values
Out[42]:
In [43]:
A[::2] # step is 2, lower and upper defaults to the beginning and end of the array
Out[43]:
In [44]:
A[:3] # first three elements
Out[44]:
In [45]:
A[3:] # elements from index 3
Out[45]:
Negative indices counts from the end of the array (positive index from the begining):
In [46]:
A = array([1,2,3,4,5])
In [47]:
A[-1] # the last element in the array
Out[47]:
In [48]:
A[-3:] # the last three elements
Out[48]:
Index slicing works exactly the same way for multidimensional arrays:
In [49]:
A = array([[n+m*10 for n in range(5)] for m in range(5)])
A
Out[49]:
In [50]:
# a block from the original array
A[1:4, 1:4]
Out[50]:
In [51]:
# strides
A[::2, ::2]
Out[51]:
Fancy indexing is the name for when an array or list is used in-place of an index:
In [52]:
row_indices = [1, 2, 3]
A[row_indices]
Out[52]:
In [53]:
col_indices = [1, 2, -1] # remember, index -1 means the last element
A[row_indices, col_indices]
Out[53]:
We can also use index masks: If the index mask is an Numpy array of data type bool
, then an element is selected (True) or not (False) depending on the value of the index mask at the position of each element:
In [54]:
B = array([n for n in range(5)])
B
Out[54]:
In [55]:
row_mask = array([True, False, True, False, False])
B[row_mask]
Out[55]:
In [56]:
# same thing
row_mask = array([1,0,1,0,0], dtype=bool)
B[row_mask]
Out[56]:
This feature is very useful to conditionally select elements from an array, using for example comparison operators:
In [57]:
x = arange(0, 10, 0.5)
x
Out[57]:
In [58]:
mask = (5 < x) * (x <= 7)
mask
Out[58]:
In [59]:
x[mask]
Out[59]:
Vectorizing code is the key to writing efficient numerical calculation with Python/Numpy. That means that as much as possible of a program should be formulated in terms of matrix and vector operations, like matrix-matrix multiplication.
We can use the usual arithmetic operators to multiply, add, subtract, and divide arrays with scalar numbers.
In [60]:
v1 = arange(0, 5)
In [61]:
v1 * 2
Out[61]:
In [62]:
v1 + 2
Out[62]:
In [63]:
A * 2
Out[63]:
In [64]:
A + 2
Out[64]:
In [65]:
A + A.T
Out[65]:
Above we have used the .T to transpose the matrix object v. We could also have used the transpose function to accomplish the same thing.
When we add, subtract, multiply and divide arrays with each other, the default behaviour is element-wise operations:
In [66]:
A * A # element-wise multiplication
Out[66]:
In [67]:
v1 * v1
Out[67]:
If we multiply arrays with compatible shapes, we get an element-wise multiplication of each row:
In [68]:
A.shape, v1.shape
Out[68]:
In [69]:
A * v1
Out[69]:
What about matrix mutiplication? There are two ways. We can either use the dot
function, which applies a matrix-matrix, matrix-vector, or inner vector multiplication to its two arguments:
In [70]:
dot(A, A)
Out[70]:
In [71]:
dot(A, v1)
Out[71]:
In [72]:
dot(v1, v1)
Out[72]:
Alternatively, we can cast the array objects to the type matrix
. This changes the behavior of the standard arithmetic operators +, -, *
to use matrix algebra.
In [73]:
M = matrix(A)
v = matrix(v1).T # make it a column vector
In [74]:
v
Out[74]:
In [75]:
M * M
Out[75]:
In [76]:
M * v
Out[76]:
In [77]:
# inner product
v.T * v
Out[77]:
In [78]:
# with matrix objects, standard matrix algebra applies
v + M*v
Out[78]:
If we try to add, subtract or multiply objects with incomplatible shapes we get an error:
In [79]:
v = matrix([1,2,3,4,5,6]).T
In [80]:
shape(M), shape(v)
Out[80]:
In [81]:
M * v
See also the related functions: inner
, outer
, cross
, kron
, tensordot
. Try for example help(kron)
.
In [82]:
M = array([[1, 2], [3, 4]])
In [83]:
inv(M) # equivalent to M.I
Out[83]:
In [84]:
dot(inv(M), M)
Out[84]:
In [85]:
det(M)
Out[85]:
In [86]:
det(inv(M))
Out[86]:
Often it is useful to store datasets in Numpy arrays. Numpy provides a number of functions to calculate statistics of datasets in arrays.
In [87]:
d = arange(0, 10)
d
Out[87]:
In [88]:
mean(d)
Out[88]:
In [89]:
std(d), var(d)
Out[89]:
In [90]:
d.min()
Out[90]:
In [91]:
d.max()
Out[91]:
In [92]:
# sum up all elements
sum(d)
Out[92]:
In [93]:
# product of all elements
prod(d+1)
Out[93]:
In [94]:
# cummulative sum
cumsum(d)
Out[94]:
In [95]:
# cummulative product
cumprod(d+1)
Out[95]:
In [96]:
A
Out[96]:
In [97]:
# same as: diag(A).sum()
trace(A)
Out[97]:
When functions such as min
, max
, etc. are applied to a multidimensional arrays, it is sometimes useful to apply the calculation to the entire array, and sometimes only on a row or column basis. Using the axis
argument we can specify how these functions should behave:
In [98]:
M = rand(3,4)
M
Out[98]:
In [99]:
# global max
M.max()
Out[99]:
In [100]:
# max in each column
M.max(axis=0)
Out[100]:
In [101]:
# max in each row
M.max(axis=1)
Out[101]:
Many other functions and methods in the array
and matrix
classes accept the same (optional) axis
keyword argument.
The shape of an Numpy array can be modified without copying the underlaying data, which makes it a fast operation even for large arrays.
In [102]:
M
Out[102]:
In [103]:
n, m = M.shape
n, m
Out[103]:
In [104]:
N = M.reshape((6, 2))
N
Out[104]:
In [105]:
O = M.reshape((1, 12))
O
Out[105]:
In [106]:
N[0:2,:] = 1 # modify the array
N
Out[106]:
In [107]:
M # and the original variable is also changed. B is only a different view of the same data
Out[107]:
In [108]:
O
Out[108]:
We can also use the function flatten
to make a higher-dimensional array into a vector. But this function create a copy of the data.
In [109]:
F = M.flatten()
F
Out[109]:
In [110]:
F[0:5] = 0
F
Out[110]:
In [111]:
M # now M has not changed, because F's data is a copy of M's, not refering to the same data
Out[111]:
Using function repeat
, tile
, vstack
, hstack
, and concatenate
we can create larger vectors and matrices from smaller ones:
In [112]:
a = array([[1, 2], [3, 4]])
In [113]:
# repeat each element 3 times
repeat(a, 3)
Out[113]:
In [114]:
# tile the matrix 3 times
tile(a, 3)
Out[114]:
In [115]:
b = array([[5, 6]])
In [116]:
concatenate((a, b), axis=0)
Out[116]:
In [117]:
concatenate((a, b.T), axis=1)
Out[117]:
In [118]:
vstack((a,b))
Out[118]:
In [119]:
hstack((a,b.T))
Out[119]:
System of linear equations like: \begin{array}{rcl} x + 2y & = & 5\\ 3x + 4y & = & 7 \end{array}
or
\begin{array}{rcl} \left[ {\begin{array}{*{20}{c}} 1&2\\ 3&4 \end{array}} \right] \left[ {\begin{array}{*{20}{c}} x\\ y \end{array}} \right] & = & \left[ {\begin{array}{*{20}{c}} 5\\ 7 \end{array}} \right] \end{array}
could be written in matrix form as $\mathbf {Ax} = \mathbf b$ and could be solved using numpy solve
:
In [120]:
A = array([[1, 2], [3, 4]])
b = array([5,7])
solve(A,b)
Out[120]:
or
In [121]:
dot(inv(A),b)
Out[121]:
To achieve high performance, assignments in Python usually do not copy the underlaying objects. This is important for example when objects are passed between functions, to avoid an excessive amount of memory copying when it is not necessary (technical term: pass by reference).
In [122]:
# now B is referring to the same array data as A
B = A
In [123]:
# changing B affects A
B[0,0] = 10
B
Out[123]:
In [124]:
A
Out[124]:
If we want to avoid this behavior, so that when we get a new completely independent object B
copied from A
, then we need to do a so-called "deep copy" using the function copy
:
In [125]:
B = copy(A)
In [126]:
# now, if we modify B, A is not affected
B[0,0] = -5
B
Out[126]:
In [127]:
A
Out[127]:
Generally, we want to avoid iterating over the elements of arrays whenever we can (at all costs). The reason is that in a interpreted language like Python (or MATLAB), iterations are really slow compared to vectorized operations.
However, sometimes iterations are unavoidable. For such cases, the Python for
loop is the most convenient way to iterate over an array:
In [128]:
v = array([1,2,3,4])
for element in v:
print(element)
In [129]:
M = array([[1,2], [3,4]])
for row in M:
print('Row', row)
for element in row:
print('Element', element)
When we need to iterate over each element of an array and modify its elements, it is convenient to use the enumerate
function to obtain both the element and its index in the for
loop:
In [130]:
for row_idx, row in enumerate(M):
print("row_idx", row_idx, "row", row)
for col_idx, element in enumerate(row):
print("col_idx", col_idx, "element", element)
# update the matrix M: square each element
M[row_idx, col_idx] = element ** 2
In [131]:
# each element in M is now squared
M
Out[131]:
When using arrays in conditions,for example if
statements and other boolean expressions, one needs to use any
or all
, which requires that any or all elements in the array evalutes to True
:
In [132]:
M
Out[132]:
In [133]:
if (M > 5).any():
print("at least one element in M is larger than 5")
else:
print("no element in M is larger than 5")
In [134]:
if (M > 5).all():
print("all elements in M are larger than 5")
else:
print("all elements in M are not larger than 5")
In [135]:
from IPython.core.display import HTML
def css_styling():
styles = open("./css/sg2.css", "r").read()
return HTML(styles)
css_styling()
Out[135]: