A Volume Knob for Every Map

Convolutional ArchitecturesMedium+20 XP+20

A Volume Knob for Every Map

Every feature map in a CNN answers one question about the image, such as "is there fur here?" or "is there a wheel-like shape here?". Not every question matters equally for every photo. A squeeze-and-excitation block lets the network turn some feature maps up and others down, depending on the image in front of it. It is built from pieces you already know:

  1. Squeeze. Average each of the CCC feature maps down to one number, exactly as global average pooling does. This gives a summary s1,…,sCs_1, \dots, s_Cs1​,…,sC​.
  2. Excite. Pass the summary through two small dense layers, neither with a bias. The first is narrower than CCC and uses ReLU. The second goes back to CCC outputs and uses the sigmoid σ(z)=11+e−z\sigma(z) = \dfrac{1}{1 + e^{-z}}σ(z)=1+e−z1​, so each output is a gate between 0 and 1:
hk=max⁡(0, ∑i=1Cwk,idown si),gi=σ(∑kwi,kup hk)h_k = \max\left(0,\ \sum_{i=1}^{C} w^{\text{down}}_{k,i}\, s_i\right), \qquad g_i = \sigma\left(\sum_{k} w^{\text{up}}_{i,k}\, h_k\right)hk​=max(0, i=1∑C​wk,idown​si​),gi​=σ(k∑​wi,kup​hk​)
  1. Scale. Multiply every value in feature map iii by its gate gig_igi​.

Task: write reweight_maps(maps, w_down, w_up).

  • maps is a list of CCC feature maps. Each map is a grid (a list of rows), and all maps have the same height and width.
  • w_down has one row per hidden unit kkk, and each row holds CCC weights: w_down[k][i] is wk,idownw^{\text{down}}_{k,i}wk,idown​.
  • w_up has one row per feature map iii, and each row holds one weight per hidden unit: w_up[i][k] is wi,kupw^{\text{up}}_{i,k}wi,kup​.
  • Return the reweighted maps in the same nested shape as maps, with every value rounded to 4 decimal places.

Examples

maps = [[[2, 0], [0, 2]], [[4, 4], [0, 0]]]
w_down = [[1.0, 0.5]]
w_up = [[1.0], [-1.0]]
returns [[[1.7616, 0.0], [0.0, 1.7616]], [[0.4768, 0.4768], [0.0, 0.0]]]
maps = [[[1, 3], [5, 7]], [[0, 0], [0, 4]], [[2, 2], [2, 2]]]
w_down = [[0.5, 0.0, -0.25], [-1.0, 0.5, 0.5]]
w_up = [[1.0, 0.5], [-1.0, 2.0], [0.0, 0.0]]
returns [[[0.8176, 2.4527], [4.0879, 5.723]], [[0.0, 0.0], [0.0, 0.7297]], [[1.0, 1.0], [1.0, 1.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