Many Questions, One Block

Images as DataMedium+20 XP+20

Many Questions, One Block

A layer never runs just one filter. It runs several over the same picture at once, each hunting for its own pattern, and each one sliding across the whole picture produces its own feature map. Stack those maps and you have a block with a height, a width and a depth — and the depth is the number of filters.

Task: write feature_block(image, filters), returning that block with every value rounded to 4 decimal places.

  • image is a grayscale picture: a list of rows of numbers. It is not always square, so its height and its width have to be counted separately.
  • filters is a list of filters. Each is a square grid of numbers, and every filter in one call is the same size — usually 3×3, but any size from 1×1 up to the size of the picture is legal.
  • Each filter sweeps the picture on its own. Its window starts in the top-left corner, moves one position at a time across and then down, and only ever stops where it fits entirely on the picture — so a 3×3 filter on a 5×7 picture stops at 3 × 5 positions.
  • At each stop, every pixel under the window is multiplied by the filter value sitting on top of it, and the products are added into one score. The filter is used exactly as given: nothing is flipped or rotated.
  • The block is written the way image shapes are written: height × width × depth. block[r][c] is a list holding one score per filter, in the order the filters were given — the scores every filter produced with its window's top-left corner on row r, column c of the picture.
  • A single filter still makes a block: each position then holds a list of length one.

Height × width × depth is the same order you already use for a colour photo, and that is no accident — the block is the next layer's picture. At the input, the depth held red, green and blue. From here on each position holds one answer per filter: did this patch look like a vertical edge, a horizontal edge, a blob? The next layer receives all of those answers at once.

vertical

One layer runs many filters at once, each producing its own map. Four filters means four maps — same picture, four different questions asked of it.

Examples

image = [[0, 0, 9, 9], [0, 0, 9, 9], [0, 0, 9, 9], [5, 5, 5, 5]]
filters = [[[-1, 0, 1], [-1, 0, 1], [-1, 0, 1]], [[-1, -1, -1], [0, 0, 0], [1, 1, 1]]]
returns [[[27.0, 0.0], [27.0, 0.0]], [[18.0, 6.0], [18.0, -3.0]]]
image = [[1, 2, 3, 4, 5], [0, 1, 0, 1, 0], [2, 0, 2, 0, 2]]
filters = [[[1, 2, 0], [0, 1, 0], [0, 0, -1]]]
returns [[[4.0], [8.0], [10.0]]]

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