Starting from these two lambda functions
import numpy as np
relu = (lambda x: np.maximum(0, x),
lambda x: 1 if x > 0 else 0)
Obviously the two functions work correctly when I pass a single number, but when I pass an array/list relu[0] works but not relu[1].
a = [1, 2, 3, 4]
print(relu[0](a)) # this one works
print(relu[1](a)) # not works
print([relu[1](v) for v in a]) # also works
CodePudding user response:
Many numpy functions, e.g. maximum, accept array-like
argument, i.e. types that can be converted to numpy arrays, and numpy coverts them to numpy arrays automatically.
a = [1, 2, 3, 4]
print(relu[0](a)) # a is converted from list to numpy array
Your second example raises a TypeError
TypeError: '>' not supported between instances of 'list' and 'int'
because you can't compare a list and an integer.
print(relu[1](a)) # compare a list to an integer: Fail
print([relu[1](v) for v in a]) # compare an integer to an integer: OK
CodePudding user response:
You can, if you'd use
np.where(x > 0, 1, 0)