Implement PReLU with a learnable slope per channel

Why it matters PReLU appears in face recognition and super-resolution networks where a learnable slope helps.

PReLU is a leaky ReLU whose negative slope is learned, one value per channel.

Write prelu(x, alpha, dy). x and dy are (N, C) arrays and alpha is (C,). Forward: y = x where x > 0, else alpha * x. Return (y, dx, dalpha), where dx = dy * (1 if x > 0 else alpha) and dalpha[c] = sum over the batch of dy * x where x <= 0, else 0.

Signaturedef prelu(x, alpha, dy)

Example

x = [[2, -1]], alpha = [0.1, 0.25], dy = [[1, 1]] gives y [[2, -0.25]], dx [[1, 0.25]], dalpha [0, -1].

Understand the idea

ReLU throws away all negative inputs, and a unit stuck in the negative region stops learning. PReLU lets a little of the negative side through, and the network learns how much. Think of a door that is not fully shut, with the gap size learned.

Tiny example: x = -1 with alpha = 0.25: y = -0.25. With dy = 1, dx = 0.25 (the slope) and dalpha = dy * x = -1, so gradient descent would push alpha up.

Rules: y = x if x > 0 else alpha * x; dx = dy * (1 or alpha); dalpha_c = sum of dy * x over positions where x <= 0.

PReLU was introduced in image classification CNNs and is still used in face recognition and super-resolution models.

Shapes and data flow

x, dy (N, C); alpha (C,) broadcast as (1, C); dalpha (C,)
solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

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

  • Sample 1: exampleprelu([[2.0, -1.0]], [0.1, 0.25], [[1.0, 1.0]])
  • Sample 2: batchprelu([[1.0, -2.0, 0.0], [-3.0, 4.0, -0.5]], [0.2, 0.1, 0.5], [[0.5, 1.0, 2.0], [1.0, -1.0, 1.0]])
  • Test 3: all positiveprelu([[1.0, 2.0]], [0.3, 0.3], [[2.0, 3.0]])