DAI developerLab· about 45 min· in the browser
Lab: matrix multiplication and one layer of a neural network
Implement matrix–vector and matrix–matrix multiplication with loops, verify against NumPy, and build a layer `W x + b` with ReLU.
Teaches: Matrices and matrix multiplication
Requires: Vectors
Theory
(AB)ᵢⱼ = Σₖ Aᵢₖ Bₖⱼ: row i of A times column j of B. The dimensions must match: m×n times n×p gives m×p. A layer in a network is exactly this plus a bend.
Sub-tasks
- matvec —
matvec(A, x)with lists of lists. - matmul —
matmul(A, B)— raise ValueError if the dimensions do not match. - lager (layer) —
lager(W, x, b)= ReLU(W x + b).
The starter code
runs in your browserdef matvec(A, x):
# TODO: en skalärprodukt per rad
...
def matmul(A, B):
# TODO: kontrollera dimensioner, tre loopar
...
def lager(W, x, b):
# TODO: ReLU(W x + b)
...
You write the code; tests you cannot see decide whether it holds up. Create a free account to run the lab.
Try the diagnosticCreate a free accountExpected results
matvec([[1,2],[3,4]],[5,6]) = [17, 39]; 5×3 · 3×7 → 5×7; 3×4 · 3×4 → ValueError; lager (layer) gives no negative numbers.
Common mistakes
- Swaps row and column in the inner loop.
- Forgets to check
len(A[0]) == len(B). - ReLU in the wrong place (before the bias).