Python Numpy Tutorial
Python Numpy Tutorial
Recognition
      We will use the Python programming language for all assignments in this course. Python is
      a great general-purpose programming language on its own, but with the help of a few
      popular libraries (numpy, scipy, matplotlib) it becomes a powerful environment for scientiAc
      computing.
      We expect that many of you will have some experience with Python and numpy; for the rest
      of you, this section will serve as a quick crash course both on the Python programming
      language and on the use of Python for scientiAc computing.
      Some of you may have previous knowledge in Matlab, in which case we also recommend
      the numpy for Matlab users page.
      You can also And an IPython notebook version of this tutorial here created by Volodymyr
      Kuleshov and Isaac Caswell for CS 228.
Table of contents:
               Python
                    Basic data types
                    Containers
                                  Lists
                                  Dictionaries
                              Sets
                              Tuples
                         Functions
                   Classes
               Numpy
                         Arrays
http://cs231n.github.io/python-numpy-tutorial/                                                  Page 1 of 28
Python Numpy Tutorial                                                                    22/07/2016, 11:03 am
                         Array indexing
                         Datatypes
                         Array math
                         Broadcasting
               SciPy
                         Image operations
                    MATLAB Ales
                    Distance between points
               Matplotlib
                         Plotting
                         Subplots
                         Images
      Python
      Python is a high-level, dynamically typed multiparadigm programming language. Python
      code is often said to be almost like pseudocode, since it allows you to express very
      powerful ideas in very few lines of code while being very readable. As an example, here is an
      implementation of the classic quicksort algorithm in Python:
         def quicksort(arr):
             if len(arr) <= 1:
                 return arr
             pivot = arr[len(arr) / 2]
             left = [x for x in arr if x < pivot]
             middle = [x for x in arr if x == pivot]
             right = [x for x in arr if x > pivot]
             return quicksort(left) + middle + quicksort(right)
         print quicksort([3,6,8,10,1,2,1])
         # Prints "[1, 1, 2, 3, 6, 8, 10]"
      Python versions
      There are currently two different supported versions of Python, 2.7 and 3.4. Somewhat
      confusingly, Python 3.0 introduced many backwards-incompatible changes to the language,
      so code written for 2.7 may not work under 3.4 and vice versa. For this class all code will
http://cs231n.github.io/python-numpy-tutorial/                                                   Page 2 of 28
Python Numpy Tutorial                                                                   22/07/2016, 11:03 am
You can check your Python version at the command line by running python --version .
Numbers: Integers and [oats work as you would expect from other languages:
         x = 3
         print type(x) # Prints "<type 'int'>"
         print x       # Prints "3"
         print x + 1   # Addition; prints "4"
         print x - 1   # Subtraction; prints "2"
         print x * 2   # Multiplication; prints "6"
         print x ** 2 # Exponentiation; prints "9"
         x += 1
         print x # Prints "4"
         x *= 2
         print x # Prints "8"
         y = 2.5
         print type(y) # Prints "<type 'float'>"
         print y, y + 1, y * 2, y ** 2 # Prints "2.5 3.5 5.0 6.25"
      Note that unlike many languages, Python does not have unary increment ( x++ ) or
      decrement ( x-- ) operators.
      Python also has built-in types for long integers and complex numbers; you can And all of the
      details in the documentation.
      Booleans: Python implements all of the usual operators for Boolean logic, but uses English
      words rather than symbols ( && , || , etc.):
         t = True
         f = False
         print type(t) # Prints "<type 'bool'>"
http://cs231n.github.io/python-numpy-tutorial/                                                  Page 3 of 28
Python Numpy Tutorial                                                                            22/07/2016, 11:03 am
         s = "hello"
         print s.capitalize() # Capitalize a string; prints "Hello"
         print s.upper()       # Convert a string to uppercase; prints "HELLO"
         print s.rjust(7)      # Right-justify a string, padding with spaces; prints
         print s.center(7)     # Center a string, padding with spaces; prints " hello
         print s.replace('l', '(ell)') # Replace all instances of one substring with
                                        # prints "he(ell)(ell)o"
         print ' world '.strip() # Strip leading and trailing whitespace; prints "w
      Containers
      Python includes several built-in container types: lists, dictionaries, sets, and tuples.
Lists
      A list is the Python equivalent of an array, but is resizeable and can contain elements of
      different types:
http://cs231n.github.io/python-numpy-tutorial/                                                           Page 4 of 28
Python Numpy Tutorial                                                                       22/07/2016, 11:03 am
As usual, you can And all the gory details about lists in the documentation.
      Slicing: In addition to accessing list elements one at a time, Python provides concise
      syntax to access sublists; this is known as slicing:
Loops: You can loop over the elements of a list like this:
      If you want access to the index of each element within the body of a loop, use the built-in
       enumerate function:
http://cs231n.github.io/python-numpy-tutorial/                                                      Page 5 of 28
Python Numpy Tutorial                                                                   22/07/2016, 11:03 am
         nums = [0, 1, 2, 3, 4]
         squares = []
         for x in nums:
             squares.append(x ** 2)
         print squares   # Prints [0, 1, 4, 9, 16]
         nums = [0, 1, 2, 3, 4]
         squares = [x ** 2 for x in nums]
         print squares   # Prints [0, 1, 4, 9, 16]
         nums = [0, 1, 2, 3, 4]
         even_squares = [x ** 2 for x in nums if x % 2 == 0]
         print even_squares # Prints "[0, 4, 16]"
      Dictionaries
      A dictionary stores (key, value) pairs, similar to a Map in Java or an object in Javascript.
      You can use it like this:
         d = {'cat': 'cute', 'dog': 'furry'} # Create a new dictionary with some dat
         print d['cat']       # Get an entry from a dictionary; prints "cute"
         print 'cat' in d     # Check if a dictionary has a given key; prints "True"
         d['fish'] = 'wet'    # Set an entry in a dictionary
         print d['fish']      # Prints "wet"
         # print d['monkey'] # KeyError: 'monkey' not a key of d
         print d.get('monkey', 'N/A') # Get an element with a default; prints "N/A"
http://cs231n.github.io/python-numpy-tutorial/                                                  Page 6 of 28
Python Numpy Tutorial                                                                22/07/2016, 11:03 am
You can And all you need to know about dictionaries in the documentation.
If you want access to keys and their corresponding values, use the iteritems method:
      Dictionary comprehensions: These are similar to list comprehensions, but allow you to
      easily construct dictionaries. For example:
         nums = [0, 1, 2, 3, 4]
         even_num_to_square = {x: x ** 2 for x in nums if x % 2 == 0}
         print even_num_to_square # Prints "{0: 0, 2: 4, 4: 16}"
      Sets
      A set is an unordered collection of distinct elements. As a simple example, consider the
      following:
http://cs231n.github.io/python-numpy-tutorial/                                               Page 7 of 28
Python Numpy Tutorial                                                                          22/07/2016, 11:03 am
As usual, everything you want to know about sets can be found in the documentation.
      Loops: Iterating over a set has the same syntax as iterating over a list; however since sets
      are unordered, you cannot make assumptions about the order in which you visit the
      elements of the set:
      Set comprehensions: Like lists and dictionaries, we can easily construct sets using set
      comprehensions:
Tuples
      A tuple is an (immutable) ordered list of values. A tuple is in many ways similar to a list; one
      of the most important differences is that tuples can be used as keys in dictionaries and as
      elements of sets, while lists cannot. Here is a trivial example:
http://cs231n.github.io/python-numpy-tutorial/                                                         Page 8 of 28
Python Numpy Tutorial                                                                22/07/2016, 11:03 am
      Functions
      Python functions are deAned using the def keyword. For example:
         def sign(x):
             if x > 0:
                 return 'positive'
             elif x < 0:
                 return 'negative'
             else:
                 return 'zero'
We will often deAne functions to take optional keyword arguments, like this:
      Classes
      The syntax for deAning classes in Python is straightforward:
class Greeter(object):
http://cs231n.github.io/python-numpy-tutorial/                                               Page 9 of 28
Python Numpy Tutorial                                                                       22/07/2016, 11:03 am
                 # Constructor
                 def __init__(self, name):
                     self.name = name # Create an instance variable
                 # Instance method
                 def greet(self, loud=False):
                     if loud:
                         print 'HELLO, %s!' % self.name.upper()
                     else:
                         print 'Hello, %s' % self.name
You can read a lot more about Python classes in the documentation.
      Numpy
      Numpy is the core library for scientiAc computing in Python. It provides a high-performance
      multidimensional array object, and tools for working with these arrays. If you are already
      familiar with MATLAB, you might And this tutorial useful to get started with Numpy.
      Arrays
      A numpy array is a grid of values, all of the same type, and is indexed by a tuple of
      nonnegative integers. The number of dimensions is the rank of the array; the shape of an
      array is a tuple of integers giving the size of the array along each dimension.
      We can initialize numpy arrays from nested Python lists, and access elements using square
      brackets:
import numpy as np
http://cs231n.github.io/python-numpy-tutorial/                                                     Page 10 of 28
Python Numpy Tutorial                                                                   22/07/2016, 11:03 am
import numpy as np
You can read about other methods of array creation in the documentation.
      Array indexing
      Numpy offers several ways to index into arrays.
      Slicing: Similar to Python lists, numpy arrays can be sliced. Since arrays may be
      multidimensional, you must specify a slice for each dimension of the array:
http://cs231n.github.io/python-numpy-tutorial/                                                 Page 11 of 28
Python Numpy Tutorial                                                                   22/07/2016, 11:03 am
import numpy as np
         #   Use slicing to pull out the subarray consisting of the first 2 rows
         #   and columns 1 and 2; b is the following array of shape (2, 2):
         #   [[2 3]
         #    [6 7]]
         b   = a[:2, 1:3]
      You can also mix integer indexing with slice indexing. However, doing so will yield an array
      of lower rank than the original array. Note that this is quite different from the way that
      MATLAB handles array slicing:
import numpy as np
         # Two ways of accessing the data in the middle row of the array.
         # Mixing integer indexing with slices yields an array of lower rank,
         # while using only slices yields an array of the same rank as the
         # original array:
         row_r1 = a[1, :]    # Rank 1 view of the second row of a
         row_r2 = a[1:2, :] # Rank 2 view of the second row of a
         print row_r1, row_r1.shape # Prints "[5 6 7 8] (4,)"
         print row_r2, row_r2.shape # Prints "[[5 6 7 8]] (1, 4)"
http://cs231n.github.io/python-numpy-tutorial/                                                 Page 12 of 28
Python Numpy Tutorial                                                                      22/07/2016, 11:03 am
      Integer array indexing: When you index into numpy arrays using slicing, the resulting
      array view will always be a subarray of the original array. In contrast, integer array indexing
      allows you to construct arbitrary arrays using the data from another array. Here is an
      example:
import numpy as np
         # When using integer array indexing, you can reuse the same
         # element from the source array:
         print a[[0, 0], [1, 1]] # Prints "[2 2]"
      One useful trick with integer array indexing is selecting or mutating one element from each
      row of a matrix:
import numpy as np
http://cs231n.github.io/python-numpy-tutorial/                                                    Page 13 of 28
Python Numpy Tutorial                                                                        22/07/2016, 11:03 am
      Boolean array indexing: Boolean array indexing lets you pick out arbitrary elements of an
      array. Frequently this type of indexing is used to select the elements of an array that satisfy
      some condition. Here is an example:
import numpy as np
http://cs231n.github.io/python-numpy-tutorial/                                                      Page 14 of 28
Python Numpy Tutorial                                                                       22/07/2016, 11:03 am
      For brevity we have left out a lot of details about numpy array indexing; if you want to know
      more you should read the documentation.
      Datatypes
      Every numpy array is a grid of elements of the same type. Numpy provides a large set of
      numeric datatypes that you can use to construct arrays. Numpy tries to guess a datatype
      when you create an array, but functions that construct arrays usually also include an
      optional argument to explicitly specify the datatype. Here is an example:
import numpy as np
      Array math
      Basic mathematical functions operate elementwise on arrays, and are available both as
      operator overloads and as functions in the numpy module:
import numpy as np
         x = np.array([[1,2],[3,4]], dtype=np.float64)
         y = np.array([[5,6],[7,8]], dtype=np.float64)
http://cs231n.github.io/python-numpy-tutorial/                                                     Page 15 of 28
Python Numpy Tutorial                                                                 22/07/2016, 11:03 am
import numpy as np
         x = np.array([[1,2],[3,4]])
         y = np.array([[5,6],[7,8]])
http://cs231n.github.io/python-numpy-tutorial/                                               Page 16 of 28
Python Numpy Tutorial                                                                  22/07/2016, 11:03 am
         v = np.array([9,10])
         w = np.array([11, 12])
         # Matrix / vector product; both produce the rank 1 array [29 67]
         print x.dot(v)
         print np.dot(x, v)
      Numpy provides many useful functions for performing computations on arrays; one of the
      most useful is sum :
import numpy as np
x = np.array([[1,2],[3,4]])
      You can And the full list of mathematical functions provided by numpy in the
      documentation.
      Apart from computing mathematical functions using arrays, we frequently need to reshape
      or otherwise manipulate data in arrays. The simplest example of this type of operation is
      transposing a matrix; to transpose a matrix, simply use the T attribute of an array object:
import numpy as np
         x = np.array([[1,2], [3,4]])
         print x    # Prints "[[1 2]
http://cs231n.github.io/python-numpy-tutorial/                                                Page 17 of 28
Python Numpy Tutorial                                                                  22/07/2016, 11:03 am
                               #          [3 4]]"
         print x.T             # Prints "[[1 3]
                               #          [2 4]]"
      Numpy provides many more functions for manipulating arrays; you can see the full list in
      the documentation.
      Broadcasting
      Broadcasting is a powerful mechanism that allows numpy to work with arrays of different
      shapes when performing arithmetic operations. Frequently we have a smaller array and a
      larger array, and we want to use the smaller array multiple times to perform some operation
      on the larger array.
      For example, suppose that we want to add a constant vector to each row of a matrix. We
      could do it like this:
import numpy as np
         # Add the vector v to each row of the matrix x with an explicit loop
         for i in range(4):
             y[i, :] = x[i, :] + v
http://cs231n.github.io/python-numpy-tutorial/                                                Page 18 of 28
Python Numpy Tutorial                                                                 22/07/2016, 11:03 am
print y
      This works; however when the matrix x is very large, computing an explicit loop in Python
      could be slow. Note that adding the vector v to each row of the matrix x is equivalent to
      forming a matrix vv by stacking multiple copies of v vertically, then performing
      elementwise summation of x and vv . We could implement this approach like this:
import numpy as np
import numpy as np
http://cs231n.github.io/python-numpy-tutorial/                                               Page 19 of 28
Python Numpy Tutorial                                                                      22/07/2016, 11:03 am
      The line y = x + v works even though x has shape (4, 3) and v has shape
        (3,) due to broadcasting; this line works as if v actually had shape (4, 3) , where
      each row was a copy of v , and the sum was performed elementwise.
           1. If the arrays do not have the same rank, prepend the shape of the lower rank array
              with 1s until both shapes have the same length.
           2. The two arrays are said to be compatible in a dimension if they have the same size in
              the dimension, or if one of the arrays has size 1 in that dimension.
           3. The arrays can be broadcast together if they are compatible in all dimensions.
           4. After broadcasting, each array behaves as if it had shape equal to the elementwise
              maximum of shapes of the two input arrays.
           5. In any dimension where one array had size 1 and the other array had size greater than
              1, the Arst array behaves as if it were copied along that dimension
      If this explanation does not make sense, try reading the explanation from the
      documentation or this explanation.
      Functions that support broadcasting are known as universal functions. You can And the list
      of all universal functions in the documentation.
import numpy as np
http://cs231n.github.io/python-numpy-tutorial/                                                   Page 20 of 28
Python Numpy Tutorial                                                               22/07/2016, 11:03 am
      Broadcasting typically makes your code more concise and faster, so you should strive to
      use it where possible.
      Numpy Documentation
      This brief overview has touched on many of the important things that you need to know
      about numpy, but is far from complete. Check out the numpy reference to And out much
      more about numpy.
SciPy
http://cs231n.github.io/python-numpy-tutorial/                                             Page 21 of 28
Python Numpy Tutorial                                                                 22/07/2016, 11:03 am
      The best way to get familiar with SciPy is to browse the documentation. We will highlight
      some parts of SciPy that you might And useful for this class.
      Image operations
      SciPy provides some basic functions to work with images. For example, it has functions to
      read images from disk into numpy arrays, to write numpy arrays to disk as images, and to
      resize images. Here is a simple example that showcases these functions:
http://cs231n.github.io/python-numpy-tutorial/                                              Page 22 of 28
Python Numpy Tutorial                                                                22/07/2016, 11:03 am
Left: The original image. Right: The tinted and resized image.
      MATLAB Ales
      The functions scipy.io.loadmat and scipy.io.savemat allow you to read and write
      MATLAB Ales. You can read about them in the documentation.
         import numpy as np
         from scipy.spatial.distance import pdist, squareform
http://cs231n.github.io/python-numpy-tutorial/                                             Page 23 of 28
Python Numpy Tutorial                                                                    22/07/2016, 11:03 am
         # [[0 1]
         # [1 0]
         # [2 0]]
         x = np.array([[0, 1], [1, 0], [2, 0]])
         print x
You can read all the details about this function in the documentation.
      Matplotlib
      Matplotlib is a plotting library. In this section give a brief introduction to the
      matplotlib.pyplot module, which provides a plotting system similar to that of
      MATLAB.
      Plotting
      The most important function in matplotlib is plot , which allows you to plot 2D data. Here
      is a simple example:
         import numpy as np
         import matplotlib.pyplot as plt
http://cs231n.github.io/python-numpy-tutorial/                                                 Page 24 of 28
Python Numpy Tutorial                                                                       22/07/2016, 11:03 am
      With just a little bit of extra work we can easily plot multiple lines at once, and add a title,
      legend, and axis labels:
         import numpy as np
         import matplotlib.pyplot as plt
         # Compute the x and y coordinates for points on sine and cosine curves
         x = np.arange(0, 3 * np.pi, 0.1)
         y_sin = np.sin(x)
         y_cos = np.cos(x)
http://cs231n.github.io/python-numpy-tutorial/                                                    Page 25 of 28
Python Numpy Tutorial                                                              22/07/2016, 11:03 am
You can read much more about the plot function in the documentation.
      Subplots
      You can plot different things in the same Agure using the subplot function. Here is an
      example:
         import numpy as np
         import matplotlib.pyplot as plt
         # Compute the x and y coordinates for points on sine and cosine curves
         x = np.arange(0, 3 * np.pi, 0.1)
         y_sin = np.sin(x)
         y_cos = np.cos(x)
# Set the second subplot as active, and make the second plot.
http://cs231n.github.io/python-numpy-tutorial/                                           Page 26 of 28
Python Numpy Tutorial                                                           22/07/2016, 11:03 am
         plt.subplot(2, 1, 2)
         plt.plot(x, y_cos)
         plt.title('Cosine')
You can read much more about the subplot function in the documentation.
      Images
      You can use the imshow function to show images. Here is an example:
         import numpy as np
         from scipy.misc import imread, imresize
         import matplotlib.pyplot as plt
         img = imread('assets/cat.jpg')
         img_tinted = img * [1, 0.95, 0.9]
http://cs231n.github.io/python-numpy-tutorial/                                         Page 27 of 28
Python Numpy Tutorial                                                  22/07/2016, 11:03 am
         cs231n
         cs231n
      karpathy@cs.stanford.edu
http://cs231n.github.io/python-numpy-tutorial/ Page 28 of 28