NumPy ArraysEasy
np.where: Choosing Elementwise
~9 mincode completion
Write clip_negatives(x) that replaces every negative value with 0 and leaves everything else alone.
You have just written the ReLU activation function, which you will meet again in the neural network sections.
Examples
Negatives become zero, positives are untouched
- Input
- clip_negatives([-2, 5, -1, 3])
- Output
- [0, 5, 0, 3]
An all-positive array is returned unchanged
- Input
- clip_negatives([1, 2, 3])
- Output
- [1, 2, 3]
An all-negative array becomes all zeros
- Input
- clip_negatives([-1, -2])
- Output
- [0, 0]
Hints
Hint 1
picks between two values elementwise without branching.
Hint 2
Watch for this: used python if on array.
Requirements
x: a NumPy array of numbersReturn an array of the same shape with negatives replaced by 0.
Constraints
Allowed library: NumPy only
Time limit: 200 ms, Memory: 64 MB
Where this shows up
~9 min
••••••••••••••••
8 employers weight this skill
3 frontier labs, 2 quant funds, 2 big tech firms, 1 autonomy company. Top match scores 68.
Python
import numpy as np
def clip_negatives(x):
"""
Replace negatives with zero, elementwise.
Args:
x: a NumPy array of numbers
Returns:
An array of the same shape with negatives replaced by 0.
"""
# YOUR CODE HERE
pass