Performant Python

Vectorisation

Overview:

  • Teaching: 5 min
  • Exercises: 15 min

Questions

  • How do I manipulate the shape or size of an array?
  • What if I want to select by indexing?

Objectives

  • Understand that by using numpy we can work directly with arrays without having to loop

Vector calculations

First as always we must import numpy:

In [2]:
import numpy as np

Let's create ourselves an array as before and change their shape.

In [5]:
a = np.arange(10).reshape( (2,5) )
b = np.arange(10).reshape( (2,5) )
print(a)
[[0 1 2 3 4]
 [5 6 7 8 9]]

Now we can begin to use numpy in 'happiness', ie use it to make our lives easier

In [6]:
c=0.1*a
print(c)
[[0.  0.1 0.2 0.3 0.4]
 [0.5 0.6 0.7 0.8 0.9]]

Now is c a copy of the original array or just a new view?

In [8]:
c[(0,0)] = -1
print(a)
print(c)
[[0 1 2 3 4]
 [5 6 7 8 9]]
[[-1.   0.1  0.2  0.3  0.4]
 [ 0.5  0.6  0.7  0.8  0.9]]
In [7]:
c.base is a
Out[7]:
False

'Multiplication'

Now that we have operated on a single array let's multiply to arrays together

In [9]:
print(a*b)
[[ 0  1  4  9 16]
 [25 36 49 64 81]]

What has just happend? This is not a vector or matrix multiplication but an element by element product. What happens when the two arrays or vectors are not of the same shape, size or length?

Dot product

If we want to perform a well defined operation such as a dot product then we need to construct this properly, for two (non-square) arrays of the same shape, the dot product is defined if:

$a \cdot b^T$

We can perform this using numpy with:

In [10]:
print(a.dot(b.T))
[[ 30  80]
 [ 80 255]]

Calculate the cross product:

$a \times b^T$

for two arrays [2,3,4] and [5,6,7]

Solution

Explore

Take the time to explore other built-in numpy functions and mathematical operations. As always, as far as possible we want to make use of existing functionality rather than reinvent the wheel.

Key Points:

  • Numpy allows you to perform vector operations on arrays without implicitly looping
  • If you have two arrays * performs an element by element product
  • Understanding how functions work, whether they operate on individual objects or the class is key to using numpy effectively