Exercises

These exercises ask you to predict and verify array computation shapes.

Exercise: Elementwise operation

Edit the code so it prints [11 22 33].

Add corresponding elements

Runs locally with Python in your browser.

Ready to run.

Hint

Use a + b.

Solution

One fix is:

NumPy adds corresponding positions: [1 + 10, 2 + 20, 3 + 30].

Exercise: Broadcast a bias

Edit the code so it prints [[11 22 33].

Add one bias vector to every row

Runs locally with Python in your browser.

Ready to run.

Hint

X.shape is (2, 3) and bias.shape is (3,). Add them directly.

Solution

One fix is:

The bias vector is added to each row.

Exercise: Matrix-vector shape

If X.shape is (6, 4) and w.shape is (4,), what is the shape of X @ w?

Answer it first, then check.

Hint

Use the rule (rows, features) @ (features,) -> (rows,).

Solution

The shape is:

(6,)

The four-feature dimension is consumed by the length-four weight vector.

Exercise: Compute row scores

Edit the code so it prints [12 34 56].

Batch linear scores

Runs locally with Python in your browser.

Ready to run.

Hint

Use the @ operator:

X @ w
Solution

One fix is:

Manual check for the first row:

1*10 + 2*1 = 12
Exercise: Matrix-matrix shape

What is the shape of (8, 3) @ (3, 5)?

Answer it first, then check.

Hint

For (m, n) @ (n, p), the result is (m, p).

Solution

The shape is:

(8, 5)

The inner dimensions match:

(8, 3) @ (3, 5)

The outer dimensions remain.