Implement ELU and its derivative

Why it matters Smooth activations like ELU and its relatives avoid dead units in small MLP heads.

ELU is smooth below zero, so negative inputs still pass a small gradient.

Write elu(x, alpha=1.0). Return (y, dy) where y = x for x > 0 and alpha * (exp(x) - 1) otherwise, and dy is the derivative: 1 for x > 0 and alpha * exp(x) otherwise.

Signaturedef elu(x, alpha=1.0)

Example

elu([1, 0, -1]) gives y [1, 0, -0.6321] and dy [1, 1, 0.3679].

Understand the idea

ELU acts like the identity for positive inputs, but for negative inputs it curves smoothly down toward -alpha instead of cutting to zero like ReLU. That keeps a small gradient alive for negative values and pushes mean activations closer to zero. Worked example with alpha = 1: at x = 2, y = 2 and dy = 1. At x = -2, y = e^-2 - 1 = 0.1353 - 1 = -0.8647, and dy = e^-2 = 0.1353. With alpha = 0.5 at x = -1, y = 0.5 * (0.3679 - 1) = -0.316 and dy = 0.5 * 0.3679 = 0.184. Rule: for x > 0, y = x and dy = 1. Otherwise y = alpha * (exp(x) - 1) and dy = alpha * exp(x). Note that x = 0 falls in the second branch, where y is 0 and dy equals alpha. A handy check: on the negative branch dy = y + alpha. The derivative is not the activation itself. Used in: some CNNs and VAEs, and as a building block for SELU in self-normalising networks.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

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

  • Sample 1: exampleelu([1, 0, -1])
  • Sample 2: alpha 2elu([-2, 3], 2.0)
  • Test 3: large positiveelu([50.0, -50.0])