Exercises

ex-sp-ch05-01

Easy

Create a 5x4 array of float64 zeros. Print its shape, dtype, strides, and total number of bytes. Verify it is C-contiguous.

ex-sp-ch05-02

Easy

Given a = np.arange(20).reshape(4, 5), use boolean indexing to extract all elements greater than 10 and less than 18.

ex-sp-ch05-03

Easy

Add a bias vector b = np.array([1, 2, 3]) to every row of a matrix X = np.ones((5, 3)) using broadcasting (no loops).

ex-sp-ch05-04

Easy

Replace a Python loop that computes the ReLU function (max(0, x) for each element) with a single vectorized call.

ex-sp-ch05-05

Easy

Generate 1000 samples from a Gaussian distribution with mean 5 and standard deviation 2 using the modern Generator API. Compute and print the sample mean and standard deviation.

ex-sp-ch05-06

Medium

For a = np.arange(24).reshape(2, 3, 4), compute the strides by hand for both C-order and Fortran-order. Verify with NumPy.

ex-sp-ch05-07

Medium

Use np.ix_ to extract a 3x3 sub-matrix from a 6x6 matrix, selecting rows [0, 2, 5] and columns [1, 3, 4]. Verify the result is a copy.

ex-sp-ch05-08

Medium

Compute the outer product of two vectors u = [1, 2, 3] and v = [4, 5, 6, 7] using: (a) broadcasting, (b) np.outer, and (c) np.einsum. Verify all three give the same result.

ex-sp-ch05-09

Medium

Replace the following loop with a vectorized version using np.select:

result = np.empty(len(x))
for i in range(len(x)):
    if x[i] < -1:
        result[i] = -1
    elif x[i] > 1:
        result[i] = 1
    else:
        result[i] = x[i] ** 3

ex-sp-ch05-10

Medium

Create a structured array with fields (id: int32, x: float64, y: float64, label: U5) and populate it with 10 random points. Sort by the x field.

ex-sp-ch05-11

Medium

Generate 4 independent streams of 1000 Gaussian samples using SeedSequence.spawn(). Verify that the streams are uncorrelated by computing pairwise correlation coefficients.

ex-sp-ch05-12

Hard

Implement a function sliding_window_view(a, window_size) that returns a 2-D array where row i contains a[i:i+window_size], using only stride manipulation (no loops, no copying).

Hint: np.lib.stride_tricks.as_strided can create a view with custom strides.

ex-sp-ch05-13

Hard

Compute the pairwise Euclidean distance matrix for n points in d dimensions using three different methods: (a) broadcasting, (b) einsum, and (c) scipy.spatial.distance.cdist. Benchmark all three for n=1000, d=3.

ex-sp-ch05-14

Hard

Use np.einsum to implement batch matrix multiplication: given A of shape (batch, m, k) and B of shape (batch, k, n), compute C of shape (batch, m, n) where C[i] = A[i] @ B[i]. Verify against np.matmul.

ex-sp-ch05-15

Hard

Write a function that generates circularly-symmetric complex Gaussian noise with a given spatial covariance matrix C\mathbf{C} (shape (n_antennas, n_antennas)). Generate 10,000 samples and verify the sample covariance matches C\mathbf{C}.

ex-sp-ch05-16

Hard

Create a memory-mapped file containing a 10,000 x 100 float32 array. Write data in chunks of 1,000 rows, then memory-map it read-only and compute column-wise statistics without loading the entire file.

ex-sp-ch05-17

Challenge

Implement a vectorized 2-D convolution (no loops) using stride tricks. Given an image of shape (H, W) and a kernel of shape (kH, kW), create a view of all patches using as_strided, then compute the convolution with a single einsum call.

ex-sp-ch05-18

Challenge

Benchmark the performance difference between iterating over rows (axis 0) vs columns (axis 1) for both C-contiguous and Fortran-contiguous arrays. Create a 5000x5000 matrix and measure the time to compute row sums and column sums for each layout. Explain the results in terms of cache behavior.

ex-sp-ch05-19

Challenge

Implement a Monte Carlo simulation that estimates π\pi using vectorized NumPy operations. Run it with 10710^7 samples. Then run 100 independent trials with different seeds to estimate the standard error and construct a 95% confidence interval for π\pi.

ex-sp-ch05-20

Challenge

Use np.einsum to compute the following tensor operations without any loops:

  1. Trace of a matrix: tr(A)\text{tr}(A)
  2. Matrix-vector product: AxA\mathbf{x}
  3. Quadratic form: xTAx\mathbf{x}^T A \mathbf{x}
  4. Batch outer products: given vectors u[i] and v[i] (both shape (batch, d)), compute all outer products u[i] v[i]^T
  5. Tensor contraction: contract a 4-D tensor T[i,j,k,l] with a matrix M[k,m] along axis k

Verify each result against explicit NumPy operations.