Skip to content

← CNNs from Scratch step 8 of 15

Medium Research

Squeeze-and-Excitation Block

A squeeze-and-excitation block computes one gate per channel, then uses that gate to scale every spatial position in the channel. The gates depend on the input, so different inputs can receive different channel weights.

Implement se_block(x, W1, W2) for one example, with its spatial dimensions already flattened into a single axis.

Inputs and output

  • x has shape (C, S): C channels and S spatial positions per channel.
  • W1 has shape (D, C) and W2 has shape (C, D).
  • C, S and D are positive integers. D is the hidden width, supplied by the weight shapes; there is no separate reduction-ratio argument.
  • All inputs are floating-point tensors. Return a tensor of shape (C, S).

Computation

  1. Squeeze: average each channel over its S positions. This gives z with shape (C,). Do not average across channels.
  2. Excitation: compute h = ReLU(W1 @ z), with shape (D,), then g = sigmoid(W2 @ h), with shape (C,). Both weight matrices belong to this step. ReLU replaces negative values with zero.
  3. Scale: return out[c, s] = x[c, s] * g[c]. Reshape the gates to (C, 1) so each gate broadcasts across its channel's positions.

Sigmoid acts independently on each channel; the gates do not need to sum to one. A gate closer to zero suppresses that channel more strongly. There are no biases or residual additions in this exercise.

For example, if the excitation output before sigmoid is zero in every channel, every gate is 0.5 and the result is x / 2. Negative input features remain negative when multiplied by a positive gate.

This exercise implements the channel-gating operation from Squeeze-and-Excitation Networks (Hu et al., 2018).