From Pixels to Class Scores

Convolutional ArchitecturesHard+30 XP+30

From Pixels to Class Scores

LeNet's recipe was conv, pool, conv, pool, dense. VGG's building block was a few 3×3 convolutions followed by a pool. Here you run a tiny network made of one VGG-style block (two 3×3 convolutions, then a pool) and a dense head, end to end, on a grayscale image.

The network, in order:

  1. Conv 1. k1 holds F1F_1F1​ filters, each a 3×3 grid, and b1 holds one bias per filter. Each filter slides over the image with no padding and stride 1. At every position, multiply each pixel by the filter value sitting on top of it, then add the nine products and the bias. That gives F1F_1F1​ feature maps. Apply ReLU.
  2. Conv 2. k2 holds F2F_2F2​ filters, with biases b2. Each filter spans the full depth of its input, so it is a list of F1F_1F1​ grids of 3×3, one grid per Conv 1 map. At every position, add up the products over all F1F_1F1​ maps, then add the bias. That gives F2F_2F2​ feature maps. Apply ReLU.
  3. Max pool. 2×2 windows with stride 2, on each map separately. If a map has an odd number of rows or columns, the leftover last row or column is dropped.
  4. Flatten. All of pooled map 0 row by row, then all of pooled map 1 row by row, and so on.
  5. Dense head. w has one row of weights per class and b one bias per class. Class ccc scores ∑iwci flati+bc\sum_i w_{ci} \, \text{flat}_i + b_c∑i​wci​flati​+bc​.

Task: write cnn_forward(image, k1, b1, k2, b2, w, b) returning the list of class scores (no softmax), each rounded to 4 decimal places.

The image is a list of rows of numbers. Every test passes an image large enough to survive both convolutions and the pool, and a w whose rows match the flattened length.

Examples

image = [[0, 1, 2, 3, 4, 5], [1, 0, 1, 0, 1, 0], [2, 2, 0, 0, 2, 2], [0, 3, 0, 3, 0, 3], [1, 1, 1, 1, 1, 1], [5, 4, 3, 2, 1, 0]]
k1 = [[[1, 0, -1], [1, 0, -1], [1, 0, -1]]]
b1 = [0.5]
k2 = [[[[0.1, 0.2, 0.1], [0.0, 0.5, 0.0], [-0.1, 0.2, -0.1]]]]
b2 = [-0.2]
w = [[1.5], [-0.5]]
b = [0.1, 0.3]
returns [2.8, -0.6]
image = [[(r * 3 + c * 5) % 7 - 3 for c in range(6)] for r in range(6)]
k1 = [[[0, 1, 0], [1, -4, 1], [0, 1, 0]], [[1, 1, 1], [0, 0, 0], [-1, -1, -1]]]
b1 = [0.0, 1.0]
k2 = [[[[0.1, 0, 0.1], [0, 0.2, 0], [0.1, 0, 0.1]], [[0, -0.1, 0], [0.1, 0, 0.1], [0, -0.1, 0]]], [[[-0.2, 0.1, 0], [0, 0.1, 0], [0, 0.1, -0.2]], [[0.05, 0.05, 0.05], [0.05, 0.05, 0.05], [0.05, 0.05, 0.05]]]]
b2 = [0.0, 0.3]
w = [[1.0, -1.0], [0.5, 0.5], [-0.25, 2.0]]
b = [0.0, 0.1, -0.1]
returns [1.5, 4.25, 5.475]

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run