Skip to content

← Activations step 4 of 9

Easy Primitives

Implement Leaky ReLU

Leaky ReLU keeps positive inputs unchanged and multiplies negative inputs by a slope called alpha. Unlike ReLU, it can retain a small negative output instead of setting every negative value to zero.

output = x          when x > 0
output = alpha * x  otherwise

With alpha=0.01, input [-2.0, -1.0, 0.0, 1.0, 2.0] becomes [-0.02, -0.01, 0.0, 1.0, 2.0]. With alpha=0.2, an input of -3.0 instead becomes -0.6. Alpha controls the negative-side slope; it does not scale the positive side.

Your task

Implement leaky_relu(x, alpha=0.01) for a floating-point tensor of any shape. Use the supplied scalar alpha when present and the default 0.01 otherwise. Return a tensor with the same shape, applying the rule independently to each element. Zero remains zero in either branch.

Use basic operations such as an elementwise where. Do not call torch.nn.functional.leaky_relu or jax.nn.leaky_relu. A tensor condition selects values for every element; a Python if cannot make a separate choice for every entry of a multi-element tensor.

The visualization uses alpha=0.01 and compares it with ReLU. Tests can supply a different alpha, so do not hard-code the slope from the plot.

Loading visualization…