Python for Artificial Intelligence Advanced 15 minutes

NumPy

Multidimensional arrays, vectorized operations and broadcasting: the foundation of scientific computing in Python.

Your progress in the track0%

Why NumPy?

Python lists are flexible but slow for large numerical operations. NumPy provides an array ndarray of a single type stored contiguously in memory, with operations written in C. Most AI libraries build on this model or are compatible with it.

Creating arrays

import numpy as np

a = np.array([1, 2, 3])
m = np.array([[1, 2, 3], [4, 5, 6]])
np.zeros((2, 3))
np.ones(4)
np.arange(0, 10, 2)        # [0 2 4 6 8]
np.linspace(0, 1, 5)       # five evenly spaced values
rng = np.random.default_rng(42)
rng.normal(size=(3, 2))    # random values from a normal distribution

Shape and dimensions

m.shape    # (2, 3)
m.ndim     # 2
m.dtype    # int64 (depending on the platform)
m.reshape(3, 2)
m.T        # the transpose

Vectorized operations

x = np.array([1.0, 2.0, 3.0])
x * 2          # [2. 4. 6.]
x ** 2         # [1. 4. 9.]
np.exp(x)
x.mean(), x.std(), x.sum()

No loop is needed; the operation is applied to all elements.

Broadcasting

X = np.array([[1, 2], [3, 4], [5, 6]])   # (3, 2)
mu = X.mean(axis=0)                     # (2,) the mean of each column
X_centered = X - mu                     # broadcast over each row

This last line is the essence of centring data before many algorithms.

Boolean indexing

scores = np.array([0.4, 0.9, 0.7, 0.2])
scores[scores > 0.5]          # [0.9 0.7]
(scores > 0.5).astype(int)    # [0 1 1 0]

Linear algebra

W = np.array([[0.5, -1.0], [2.0, 0.1]])
v = np.array([1.0, 2.0])
W @ v                 # matrix-vector multiplication
np.linalg.inv(W)
np.linalg.norm(v)

The operator @ is matrix multiplication, the core operation in neural network layers.

Lesson terms

Broadcasting
Rules that allow operations between arrays of different shapes by implicitly stretching compatible dimensions.
Vectorized operations
Applying the operation to the whole array at once instead of looping over the elements.
The ndarray
NumPy's basic data structure: a grid of values of a single type with a specific shape.

Abstract

NumPy is the core numerical computing library in Python. It offers the multidimensional ndarray with a single data type, vectorized operations that run efficiently without explicit loops, and broadcasting rules for operations between arrays of different dimensions, in addition to linear algebra and statistics functions.

Review questions

  1. What is the shape of the result of adding an array of shape (3, 4) to an array of shape (4,)?

    (3, 4), since the vector is broadcast over each row.

  2. Why are vectorized operations preferred over loops?

    Because they run internally in optimized compiled code, so they are much faster and clearer.

Sources and references

  1. NumPy: the absolute basics for beginners
  2. Broadcasting — NumPy User Guide
  3. Harris et al. (2020) Array programming with NumPy — Nature

Complete the lesson