← back

Implement ReLU Activation Function

#42 · Deep Learning · Easy

⊣ Solve on deep-ml.com

Problem

Implement the ReLU (Rectified Linear Unit) activation function. Given a list or array of values, return a new array where each negative value is replaced with 0 and positive values remain unchanged.

Solution

1
2
3
4
import numpy as np

def relu(z):
    return np.maximum(0, np.array(z, dtype=np.float64)).tolist()

Explanation

  1. Convert the input to a NumPy array.
  2. Use np.maximum(0, z) to element-wise compare each value with 0 and keep the larger one.
  3. Negative values become 0; positive values are unchanged.

Complexity

  • Time: O(n) where n is the number of elements
  • Space: O(n) for the output array