Lecture 22

Numpy II

MCS 275 Spring 2024
Emily Dumas

View as:   Presentation   ·   PDF-exportable  ·   Printable

Lecture 22: Numpy II

Reminders and announcements:

  • Homework 6 grades coming soon
  • Project 2 solution will be posted today
  • python3 -m pip install matplotlib

Where we left off

The numpy module is used for multidimensional typed arrays.

Vectors (1D arrays) and matrices (2D arrays) are the most frequently used.

Last time we explored ways to make arrays and access elements.

Let's continue working in the numpy introduction notebook

Missed last time

2D arrays: identity matrix, transpose

Bool gotcha

np.array([5,0,1])==np.array([0,0,0])

evaluates to

np.array([False,True,False])

and numpy arrays do not support boolean coercion so this cannot appear in if.

To test if two arrays are equal, use one of:

np.all(A==B)
np.array_equal(A,B)

Ufuncs

Numpy's "ufuncs" or universal functions are functions that can be applied directly to arrays, automatically acting on each element.

Numpy provides a lot of these. Some built-in Python operations work this way, too.

Usually, ufuncs allow you to avoid explicit iteration over array elements (which is much slower).

Broadcasting

If an operation expects arrays of the same dimension, but different dimensions are given, numpy attempts to fix this by broadcasting—using duplication to extend an array to a higher dimension.

E.g. A+1 works when A is a numpy array. It adds 1 to each entry. But how?

Broadcasting first turns 1 into an array with the same shape as A where each entry is 1.

Details on the rules for broadcasting in VanderPlas.

Aggregations

Numpy has operations like sum, product, max, min, all, any, that reduce array dimension.

Masks

Suppose:

  • A is an array
  • M is an array of bool of same shape

Then A[M] gives a vector that lists all elements of A at positions where M is True.

Often used to test or modify elements of an array that meet certain criteria, e.g. A[A>5]=5.

Image support

Array to image: Pillow has Image.fromarray(...)

Image to array: np.array(...) accepts images.

SLOW: Image + getpixel / putpixel

FAST: Image → array → processed array → Image

References

Revision history

  • 2023-03-07 Finalization of the 2023 lecture this was based on
  • 2024-02-28 Initial publication