Apply instance normalization to images

Why it matters Instance norm is standard in style transfer and image-to-image GAN generators.

Style transfer networks normalise every image and channel on its own, so one picture's contrast does not leak into another's.

Write instance_norm(x, gamma, beta, eps=1e-5). x is (N, C, H, W); gamma and beta are (C,). For each sample and each channel, compute the mean and biased variance over (H, W) only, normalise, and return gamma * x_hat + beta.

Signaturedef instance_norm(x, gamma, beta, eps=1e-5)

Example

x = [[[[0, 2], [4, 6]]]] (shape (1, 1, 2, 2)), gamma = [1], beta = [0] gives about [[[[-1.3416, -0.4472], [0.4472, 1.3416]]]].

Understand the idea

Different images can have very different brightness and contrast. Instance norm wipes those out per image and per channel, keeping only the pattern. It is like adjusting each photo's exposure separately before comparing them.

Tiny example: one channel with pixels 0, 2, 4, 6. Mean 3, variance (9 + 1 + 1 + 9) / 4 = 5, std 2.236. Normalised: -1.342, -0.447, 0.447, 1.342.

Rule: for each (n, c): mean and var over (H, W); y = gamma_c * (x - mean) / sqrt(var + eps) + beta_c.

Comparison: batch norm pools over (N, H, W), layer norm over (C, H, W), instance norm over (H, W), and group norm over a group of channels plus (H, W).

Fast style transfer and pix2pix-style generators use instance norm.

Shapes and data flow

x (N,C,H,W) -> stats (N,C,1,1) -> y (N,C,H,W)
solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 3.

  • Sample 1: exampleinstance_norm([[[[0.0, 2.0], [4.0, 6.0]]]], [1.0], [0.0])
  • Sample 2: two channelsinstance_norm(X, [1.0, 0.5], [0.0, 1.0])
  • Test 3: flat channelinstance_norm(np.full((1, 1, 2, 2), 3.0), [2.0], [1.0])