NumPy / SciPy Quiz
Please do explore beyond the problems given, and feel free to ask questions at any time.
If you need a quick refresher on NumPy, have a look at this introduction. Also see the SciPy lectures.
If you run out of exercises, there are 100 more here!
The NumPy array
Create a
3x4
array containing the numbers from 0 through 11 (usingnp.arange
andnp.reshape
), and call itx
.
Predict whether
x
changes after executing the following:
Compute the sums of the columns of x, using
np.sum
.
Construct the array x = np.array([0, 1, 2, 3], dtype=np.uint8). Predict the value of
x - 1
.
Broadcasting
Consider two arrays,
x = np.arange(5); y = np.array([0.5, 1.5])
.Construct a
5x2
matrix such thatA[i, j] = x[i] * y[j]
, without using for-loops.
Given a list of XYZ-coordinates,
p
,Normalise each coordinate by dividing with its Z (3rd) element. For example, the first row becomes:
Hint: extract the last column into a variable
z
, and then change its dimensions so thatp / z
works.
Indexing
Create a
3x3
ndarray,A = np.array([[0, 1, 2], [1, 1, 3], [2, 3, 2]])
. Find an indexing expression for extracting the diagonal elements, i.e.delems = A[...]
Generate a 10 x 3 array of random numbers (all between 0 and 1). From each row, pick the number closest to 0.75. Make use of
np.abs
andnp.argmax
to find the columnj
which contains the closest element in each row.
Predict and verify the shape of the following slicing operation.
Optimization
Consider the Rosenbrock test function. You can visualize it by executing the following cell:
Find the minimum of the test function rosenbrock
defined above. Use scipy.optimize.minimize
, and the following template:
Plotting
Generate some random data using:
Now, try to reproduce this plot:
ndimage
Use scipy.ndimage.distance_transform_edt
to calculate the distance map of the image generated in the next cell:
Display the distance map; can you interpret what you see?
interpolation
An image is sampled T
times by the code below. Take the coordinates and values of the samples, and try to reconstruct the original image. Hint: Use scipy.interpolate.griddata
, and provide it with the coordinates of the full image, generated using np.indices
.
We can visualize the data below, to see how densely the image was sampled: